Reputation: 1
So right now, I have my code set to end in any letter except "y" or "Y" (because of course, 'y' will continue the loop). I want to know how to end my loop using only the letter "n" or "N" with the equalsIgnoreCase code. But can't figure out how to add it to my project.
This is what the end of my code looks like right now:
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
Upvotes: 0
Views: 80
Reputation: 1
You can try this. Then, the loop will stop when the character entered is n or N
do{
//Your code here
}while(choice.charAt(0) == 'n' || choice.charAt(0) == 'N');
Upvotes: 0
Reputation: 131486
You should handle specifically each case.
If the choice is neither y/Y or n/N, so you know you have to warn the user of the bad input and so you loop again :
boolean mustContinue = true;
do{
...
System.out.print("Continue? (y/n): ");
String choice = sc.next();
if (choice.equalsIgnoreCase("N")){
mustContinue = false;
}
else if (!choice.equalsIgnoreCase("Y")){
System.out.println("Invalid choice :" + choice);
}
} while(mustContinue);
Upvotes: 1
Reputation: 575
if (choice.equalsIgnoreCase('n')) {break;}
Read this for better understanding: https://www.tutorialspoint.com/java/java_break_statement.htm
Upvotes: 0