I have this code
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter menu number: ");
int value = scanner.nextInt();
if (value == 1){
System.out.println("first");
} else if (value == 2) {
System.out.println("second");
} else if (value == 3) {
System.out.println("third");
} else {
System.out.println("closing program");
}
}
I want the behavior to be that when "1" is entered as a menu value and "first" is printed, the program doesn't terminate but goes back to System.out.println("Enter menu number: ");
so another menu number can be entered and so on. Don't know how exactly to go about it.
You can do something like this
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String userInput = "";
while (true) {
System.out.println("Enter menu number: ");
userInput = scanner.next();
if (userInput.trim().toUpperCase().equals("EXIT")) {
break;
}
int value = Integer.parseInt(userInput);
if(value == 1){
System.out.println("first");
}
else if(value==2){
System.out.println("second");
}
else if(value==3){
System.out.println("third");
}
}
}
Put a loop on your code:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int value = -1;
do { // Here you will loop until you enter something to "terminate"
System.out.println("Enter menu number: ");
value = scanner.nextInt();
if (value == 1){
System.out.println("first");
} else if (value==2){
System.out.println("second");
} else if(value==3){
System.out.println("third");
} else{
System.out.println("closing program");
}
} while (value != -1); // End condition
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.