Reputation: 33
first post here. I was instructed to change my code to loop back to the beginning of the array and ask the user for input again after they input something invalid (Like 0 or 5 for example). If someone could point me in the right direction, I would be thankful.
package lepackage;
import java.util.Scanner;
public class SwitchItUp {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter menu item:");
int input = scanner.nextInt();
String inputString;
switch (input) {
case 1: inputString = "User want to Enter data";
break;
case 2: inputString = "User want to Display sata";
break;
case 3: inputString = "User want to Print data";
break;
case 4: inputString = "User want to Exit";
break;
default: inputString = "Invalid Number";
break;
}
System.out.println(inputString);
}
}
Upvotes: 0
Views: 552
Reputation: 1157
how about using a label here. though It's not the cleaner approach compare to do.. while. see the code . Also don't forget to close the scanner !!
Scanner scanner = new Scanner(System.in);
int input;
badinput: while (true) {
System.out.println("Enter menu item:");
input = scanner.nextInt();
String inputString;
if ((!(input > 0 && input < 5)))
continue badinput;
else {
switch (input) {
//switch case
}
System.out.println(inputString);
break;
}
}
scanner.close();
Upvotes: 1
Reputation: 4266
I'd surround it with a do...while
loop
do {
//your code here
} while (!(input > 0 && input < 5));
Upvotes: 3