Home > database >  how to add words that must be written in data input, if the word is not input then a loop will occur
how to add words that must be written in data input, if the word is not input then a loop will occur

Time:01-21

example :

  1. Input your address [must be ended with 'street'] : red Input must be ended with 'street' !
  2. Input your address [must be ended with 'street'] : red street

how to loop the input question if the inputter does not add the word 'street'

CodePudding user response:

It could be something like this (read the comments in code):

// Keyboard input Stream. The JVM will auto-Close this when app ends.
Scanner userInput = new Scanner(System.in);  
    
// To hold supplied Address.
String address = "";
    
// Continue looping for as long as the `address` variable is empty.
while (address.isEmpty()) {
    System.out.print("Enter Address: -> ");  // Ask User for Adress:
    address = userInput.nextLine().trim();   // Get entire keyboard input line:
    /* Validating User Input using the String#matches() method and a
       small Regular Expression (RegEx): `(?i)` Letter case insensative,
       `.*` Any number of alphanumerical characters, ` street` must 
       end with a whitespace and `street` in any letter case.      */
    if (!address.matches("(?i).* street")) {
        // Not a match! Inform User and allow to try again...
        System.out.println("Invalid Address. Must end with the word "
                               "'Street'. Try Again...");
        System.out.println();
        address = "";  // Empty `address` to ensure reloop.
    }
}

// If we get to this point then validation was successful.
    
// Display the Address in Console Window:
System.out.println("Supplied Address: -> "   address);

CodePudding user response:

Have you tried anything? If not, you can break down into the following and build up your code step-by-step.

Which loop to use?

You should first choose a loop to start with. For-loop or Do-while loop?
For a For-loop, it will repeat the logic inside the loop for a given number of times.
For a Do-While loop, it will repeat until your logic does not fulfil any more.

What function can be used to read an Input?

The simplest class that can be used to read an Input will be Scanner.

How will be the code look like?

Because you know that you have to repeat your Input logic until street is being inputted at the end. So you probably end up having something like this:

Define some useful variables here if necessary
Loop Body Start (Repeat Condition here if you choose for-loop)
  Ask for Input
Loop Body End (Repeat Condition here if you choose do-while loop)

Note that the word automatically means that you can do nothing if your requirement is not met. Because a loop is meant to be repeat if your stated requirement is not yet finished.

  • Related