BlitzDrache BlitzDrache - 2 years ago 151
Java Question

Trying to validate whether or not the user typed in Yes or No

So I am trying to validate whether the user typed in a Yes or No and to continue asking until they type in one or the other. This is my code so far.

System.out.println("Would you like a Diamond instead of a Pyramid? Type Yes or No");
String input2 = scan.nextLine();
boolean d = input2.equals("Yes");
System.out.println(d);

while ((d != false) || (d != true)) {
System.out.println("Invalid Input. Please try again");
input2 = scan.nextLine();
d = input2.equals("Yes");
System.out.println(d);
}


Where am I going wrong? I am new to java. Any help would be greatly appreciated.

Edit: I am awful at writing. What I am going for is this type of logic.
Ask the user if they would like a diamond instead of a pyramid.
a. The user must type “Yes” or “No”.
b. If the user types neither of these, ask again until they provide appropriate input.

Answer Source

You are ending up having an infinite loop at

while ((d != false) ||  (d != true))

since d being a boolean even when updated would either be true or false and in both the cases would satisfy the above condition. Instead you can change it to

System.out.println("Would you like a Diamond instead of a Pyramid? Type Yes or No");        
String input2 = scan.nextLine();
boolean d = input2.equalsIgnoreCase("Yes") || input.equalsIgnoreCase("No"); // confirms if the user input is Yes/No or invalid other than that
.... 
while (!d) { // d==false ' invalid user input
    System.out.println("Invalid Input. Please try again");
    input2 = scan.nextLine();
    d = input2.equalsIgnoreCase("Yes") || input.equalsIgnoreCase("No");
    System.out.println(d); 
    // also printing a boolean would print either true or false base on your input; you migt want to perform some other action
} // this would exit on user input "Yes"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download