Ending this do-while loop?
How do I end the do-while loop when the user enters 0?
The program will continue execution if the user enter F,G,H and J. The program will exit if the user enters 0.
import java.u开发者_运维技巧til.Scanner;
public class P4Q5 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("\nMain Menu: \n" +
"Enter 0 to exit program\n" +
"Enter F to display Faith\n" +
"Enter G to display Grace\n" +
"Enter H to display Hope\n" +
"Enter J to display Joy\n");
do {
System.out.print("Enter your choice:");
String s = sc.nextLine();
char ch = s.charAt(0);
if (( ch == 'F')) {
System.out.println("\nFaith\n");
}
else if (( ch == 'G')) {
System.out.println("\nGrace\n");
}
else if (( ch == 'H')) {
System.out.println("\nHope\n");
}
else if (( ch == 'J')) {
System.out.println("\nJoy\n");
}
else {
System.out.println("\nWrong option entered!!\n");
}
} while (ch == 'O');
// TODO code application logic here
}
}
How about while (ch != '0')
instead of while (ch == 'O')
? Notice the difference between 0
and O
?
try this in your do while:
if( ch == '0') break;
Try this:
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("\nMain Menu: \n" +
"Enter 0 to exit program\n" +
"Enter F to display Faith\n" +
"Enter G to display Grace\n" +
"Enter H to display Hope\n" +
"Enter J to display Joy\n");
do {
System.out.print("Enter your choice:");
String s = sc.nextLine();
char ch = s.charAt(0);
if (( ch == 'F')) {
System.out.println("\nFaith\n");
}
else if (( ch == 'G')) {
System.out.println("\nGrace\n");
}
else if (( ch == 'H')) {
System.out.println("\nHope\n");
}
else if (( ch == 'J')) {
System.out.println("\nJoy\n");
}
else if (( ch == 'O' )) {
System.exit();
}
else {
System.out.println("\nWrong option entered!!\n");
}
} while (ch == 'F' || ch == 'G' || ch == 'H' || ch == 'J' || ch == 'O');
// TODO code application logic here
}
To exit program you need to do System.exit()
To exit loop do as @bitmask stated
I would use a boolean variable, if you enter 0 the boolean becomes true, and then do a check on the boolean...
boolean bool = false;
do {
...
if(input == '0')
bool=true;
} while (!bool);
oh and before i forget, i would also do one input before the do while, and one at the end of the loop. Like that, your whole code won't be run again after you hit 0.
精彩评论