Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a Y/N Condition work

Tags:

java

I need help with a SIMPLE Y/N Condition for my program. I don't really get it to work as I want to.

Unfortunately all the other topics I find is very confusing. I'm a very novice student in programming.

I want a Y/N Condition that wont crash and is not CASE SENSITIVE. so if Y or y it goes back to another menu, if n and N is just stop the program and if anything else is typed in it will loop until the Y or N conditions are met.

This is what i wrote:

String input = ScanString.nextLine();

while (!"Y".equals(input) || !"y".equals(input) || !"N".equals(input) || !"n".equals(input)) {
    System.out.println("Please enter Y/N (Not case sensitive): ");
    input = ScanString.nextLine();
}

if ("Y".equals(input) || "y".equals(input)) {
    meny1();
} else if ("N".equals(input) || "n".equals(input)) {

}

When it runs, whatever I put in, it won't break the while loop.

like image 806
Rob Avatar asked Jan 08 '23 11:01

Rob


2 Answers

while (!"Y".equals(input) || !"y".equals(input) ||... means "keep looping while the input isn't 'Y' or the input isn't 'y' or...". By definition, one of those conditions will always be true.

The simplest way to do what you're looking for would be a case insensitive comparison, and an and (&&) rather than or operator:

while (!input.equalsIgnoreCase("Y") && !input.equalsIgnoreCase("N")) { 

That means "keep looping while the input isn't 'Y' or 'y' and the input isn't 'N' or 'n'.

Or the same in Yoda-speak, since you were using Yoda-speak:

while (!"Y".equalsIgnoreCase(input) && !"N".equalsIgnoreCase(input)) { 
like image 111
T.J. Crowder Avatar answered Feb 08 '23 17:02

T.J. Crowder


Try this

while (!("Y".equalsIgnoreCase(input)) && !("N".equalsIgnoreCase(input))) {

}

Or

String[] validInputs = { "Y", "N" };
while(!Arrays.asList(validInputs).contains(input.toUpperCase())) {

}
like image 27
JamesB Avatar answered Feb 08 '23 19:02

JamesB