Java: do-while loop with switch statement
Solution 1
while(x=false);
This is wrong. (should be ==)
Solution 2
Yes =
is assignment operator you have to use ==
to check equality and other than that,note here your switch can be reduce to following and currently you have redundant code you can better use if statement with ||
operator here.
switch (letter) {
case "a":
case "A":
case "b":
case "B":
case "c":
case "C":
case "d":
case "D":
case "f":
case "F":
x=true;
break;
default:
//...
Solution 3
You can simplify the switch statement even further. By converting the letter to upper case you are checking for both upper and lower case. For example:
do{
System.out.print("Enter grade (one character): ");
letter = sc.next();
switch (letter.toUpperCase()) {
case "A":
case "B":
case "C":
case "D":
case "F":
x=true;
break;
default:
System.out.println("Invalid grade - must enter A,B,C,D,F (upper or lower case)");
break;
}
} while(x==false);
System.out.println(x);
Admin
Updated on October 23, 2020Comments
-
Admin over 3 years
Language: Java
boolean x = false; String letter = "NULL"; do{ System.out.print("Enter grade (one character): "); letter = sc.next(); switch (letter) { case "a": x=true; break; case "A": x=true; break; case "b": x=true; break; case "B": x=true; break; case "c": x=true; break; case "C": x=true; break; case "d": x=true; break; case "D": x=true; break; case "f": x=true; break; case "F": x=true; break; default: System.out.println("Invalid grade - must enter A,B,C,D,F (upper or lower case)"); System.out.println(x); break; } System.out.println(x); } while(x=false);
--------------result output-----------------------------------result output--------------------------
Since I am new, I need a 10 reputation to post pictures of the output...so here is the output by typing it out...
//this is for if I enter String "e"
Enter grade (one character): e Invalid grade - must enter A,B,C,D,F (upper or lower case)
false
false
//this is for if I enter String "A"
Enter grade (one character): A
Invalid grade - must enter A,B,C,D,F (upper or lower case)
true
The question***:For my output,when I enter "e", I was hoping to see something like
Enter grade (one character): e
Invalid grade - must enter A,B,C,D,F (upper or lower case)
false
false
//loops through
Enter grade (one character):
So I was hoping that when I entered "e" it would make it false...and then start at the beginning until a result finally is entered that is: A,B,C,D,F (upper or lower case)
What is my mistake? I have been trying to brainstorm it myself, but I thought I would see what you guys have to say....
If you think the strategy I am using to get the output is not the best....What strategy/logic would you recommend?
Thanks for the help!