2

How would I use a while loop to keep asking the user to type a valid answer repeatedly until a valid input is given and end the program when a valid input is given? I only know how to use int and numbers. I am confused by letters. How should I apply the NOT operator or other logical operators || &&.

Scanner myScan = new Scanner(System.in);                                        
System.out.println("Enter food");                                       
String food = myScan.nextLine();

if (food.equalsIgnoreCase("b"))
{
    System.out.println("beans");
}
else if (food.equalsIgnoreCase("e"))                                        
{
    System.out.println("eggs");
}
else
{
    System.out.println("error");
}
sellc
  • 380
  • 1
  • 5
  • 19
fdasf
  • 31
  • 1
  • 3

4 Answers4

2

One approach would be to define a "flag" variable, then loop until it's "true". For example:

  Scanner myScan = new Scanner(System.in);
  boolean done = false;
  while (!done) {                                        
    System.out.println("Enter food");                                       
    String food = myScan.nextLine().toLowerCase();                                        
    switch (food) {
       case "b" :
         System.out.println("beans");                                      
         done = true;
         break;
       case "e" :
         System.out.println("eggs");                                       
         done = true;
         break;
       ...
       default :
         System.out.println("error");                                      
     }    
  }    
paulsm4
  • 114,292
  • 17
  • 138
  • 190
2

At a very simple level, I'd use a do-while loop, as you want to enter the loop at least once. I'd then determine the validity of the input, using a boolean flag and make further determinations based on that, for example...

Scanner myScan = new Scanner(System.in);
boolean userInputCorrect = false;
String food = null;
do {
    System.out.println("Enter food");
    food = myScan.nextLine();
    userInputCorrect = food.equalsIgnoreCase("b") || food.equalsIgnoreCase("e") || food.equalsIgnoreCase("exit");
    if (!userInputCorrect) {
        System.out.println("Error");
    }
} while (!userInputCorrect);
System.out.println("You selected " + food);

An expanded solution might use some kind of valid method, into which I can pass the String and have it validate the input based on known values, but that's probably a little beyond the scope of the question

As has been, correctly, pointed out but others, it would be more efficient to convert the input to lowercase once and compare all the values, in this case, it might be better to use a switch statement...

Scanner myScan = new Scanner(System.in);
boolean userInputCorrect = false;
String food = null;
do {
    System.out.println("Enter food");
    food = myScan.nextLine();
    switch (food.toLowerCase()) {
        case "b":
        case "e":
        case "exit":
            userInputCorrect = true;
            break;
        default:
            System.out.println("Error");
    }
} while (!userInputCorrect);
System.out.println("You selected " + food);

But you could also do...

food = myScan.nextLine().toLowerCase();
userInputCorrect = food.equals("b") || food.equals("e") || food.equals("exit");
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

you also can use Map and feel no worries about adding more food

    Scanner myScan = new Scanner(System.in);
    System.out.println("Enter food");
    String food;

    Map<String, String> foodMap = new HashMap<>();
    foodMap.put("e", "Eggs");
    foodMap.put("b", "Beans");
    // add more food
    while (true) {
        food = myScan.nextLine();
        String value = foodMap.get(food);
        if (value == null) {
            System.out.println("Error!");
            break;
        }
        System.out.println(value);
    }
Bishoy Kamel
  • 2,327
  • 2
  • 17
  • 29
-1

First of all its bad practice to use flags, what you should use is something called a Do while Loop.

do { 
//block of code to be executed
} while(booleanExpression);

A do while loop will excute the code within the do block then checks the while expression.


For your case you could do something like this:

Scanner myScan = new Scanner(System.in);  
String food;
do{
  System.out.println("Enter food");                                       
  food = (myScan.nextLine()).toLoweCase();
}while(!food.equals("b") || !food.equals("c"))

if (food.equals("b"))                                        
{                                       
 System.out.println("beans");                                      
}                                       
else if (food.equals("e"))                                        
{                                       
 System.out.println("eggs");                                       
}        

For future proofing you might have a problem if the number of foods continues to grow. Consider using an Array or Array List

Yusof Bandar
  • 169
  • 1
  • 4
  • 9
  • Conceptually you idea works, but `food != 'b' || food != 'c'` won't compile as `food` is a `String` not `char` and you shouldn't be using `!=` directly, but instead be using `!food.equals("b")` - which is probably why it's been down voted ;) – MadProgrammer Feb 05 '18 at 23:30
  • Yeah I should use `!food.equalsIgnoreCase("b")` – Yusof Bandar Feb 05 '18 at 23:32
  • Just to explain why not to use flags. The `do while` loop was created to eliminate the use of flags, it makes your code more readable. – Yusof Bandar Feb 05 '18 at 23:35
  • It's slightly more efficient to use "toLoweCase()" once, up front, than to use "equalsIgnoreCase()" for (potentially many) separate tests. Since Java 7, you can also use a switch block instead of "String.equals()" and friends. And your comments about "flags": complete and utter nonsense. An alternative to using a flag, however, is `break`. – paulsm4 Feb 05 '18 at 23:35
  • In this particular case, where you need to display an error message, it's more efficient to define a "flag" once, check it to display a error message or not and then check it again for the exit condition – MadProgrammer Feb 05 '18 at 23:51