Reputation: 57
So I've attached a debugger, and tried different inputs and I can't seem to figure out why this won't get past the loop. When ran I enter "l" or "L", then entry gets set to that, then input is set to the capitalized version and then it repeats.
public static char displayMenu(){
char input;
sc.nextLine();//clear junk
do {
System.out.println();
System.out.println("\t\t Enter L to (L)oad ");
String entry = sc.nextLine();
input = entry.toUpperCase().charAt(0);
} while (input != 'L' || input!='M' || input != 'P' || input != 'Q');
Upvotes: 2
Views: 2355
Reputation: 7334
De Morgan's laws tell us that
(input != 'L' || input!='M' || input != 'P' || input != 'Q')
is the same as
! (input == 'L' && input=='M' && input == 'P' && input == 'Q')
which must always be true because
(input == 'L' && input=='M' && input == 'P' && input == 'Q')
must always be false because
input
can only be equal to one thing at a time.
Use De Morgan's laws to avoid extra NOT's when you can. Computers don't care but humans don't process NOT's very well.
Upvotes: 0
Reputation: 1194
your have used logical or condition it needs just one true statement to run, even though you enter 'L' , at this point your one statement is false but other statements became true that why it keeps on repeating.
Upvotes: 1
Reputation: 201447
Your boolean
||
is incorrect. If a value is L
it is then not M
, P
or Q
so your loop will continue to iterate. I think you wanted something like,
while (input != 'L' && input != 'M' && input != 'P' && input != 'Q');
or
while (!(input == 'L' || input == 'M' || input == 'P' || input == 'Q'));
consider when input
is L
, clearly L
is not M
and so your initial while
condition would continue to iterate.
Upvotes: 1
Reputation: 6403
public static char displayMenu(){
char input;
sc.nextLine();//clear junk
do {
System.out.println();
System.out.println("\t\t Enter L to (L)oad ");
String entry = sc.nextLine();
input = entry.toUpperCase().charAt(0);
} while ((input != 'L') && (input!='M') && (input != 'P') && (input != 'Q'));
try this
Upvotes: 0
Reputation: 11
Like
public static void main(String[] args) {
char input;
Scanner sc = new Scanner(System.in);
input = sc.nextLine().charAt(0);//clear junk
do {
System.out.println();
System.out.println("\t\t Enter L to (L)oad ");
String entry = sc.nextLine();
input = entry.toUpperCase().charAt(0);
} while (input != 'L' && input!='M' && input != 'P' && input != 'Q');
}
Upvotes: 0
Reputation: 5949
input
will only have one value. That value cannot be both L
and M
. You need to change the termination condition.
Upvotes: 2