我试图验证switch case
语句,以确保用户不输入任何字符或字符串类型。我如何实现这一目标?我一直在尝试使用while
语句,但我无法验证它。
public static boolean showMenu()
{
// Print welcome message
System.out.println("\nApplication Menu : ");
System.out.println("[1] Help");
System.out.println("[2] Add");
System.out.println("[3] Subtract");
System.out.println("[4] Multiply");
System.out.println("[5] Divide");
System.out.println("[6] Quit");
int SelectMenu = jin.nextInt();
switch(SelectMenu)
{
case 1:
showChoice();
break;
case 2:
add();
break;
case 3:
subtract();
break;
case 4:
multiply();
break;
case 5:
divide();
break;
case 6:
return false;
}
return true;
}
您可以使用如下循环:
String line = jin.nextLine();
while(!line.matches("\\d")){
System.out.println("Nope, please enter a digit");
line = jin.nextLine();
}
int selectMenu = Integer.parseInt(line);
看看这个简单的例子并使其适应您的代码:
/**
*
* @author Momir Sarac
*/
public class SwitchExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("\nApplication Menu : ");
System.out.println("[1] Help");
System.out.println("[2] Add");
System.out.println("[3] Subtract");
System.out.println("[4] Multiply");
System.out.println("[5] Divide");
System.out.println("[6] Quit");
while (!scanner.hasNextInt()) scanner.next();
int number = scanner.nextInt();
switch (number) {
case 1:
clickedHelp();
break;
case 2:
clickedAdd();
break;
case 3:
clickedSubtract();
break;
case 4:
clickedMultiply();
break;
case 5:
clickedDivide();
break;
default:
clickedSomething();
}
}
public static void clickedHelp(){
System.out.println("Help!");
}
public static void clickedAdd(){
System.out.println("Add");
}
public static void clickedSubtract(){
System.out.println("Subtract");
}
public static void clickedMultiply(){
System.out.println("Multiply");
}
public static void clickedDivide(){
System.out.println("Divide");
}
public static void clickedSomething(){
System.out.println("Exit");
System.exit(0);
}
}
希望你需要做这样的事情
public static boolean showMenu()
{
while(true) {
// Print welcome message
System.out.println("\nApplication Menu : ");
System.out.println("[1] Help");
System.out.println("[2] Add");
System.out.println("[3] Subtract");
System.out.println("[4] Multiply");
System.out.println("[5] Divide");
System.out.println("[6] Quit");
int SelectMenu = jin.nextInt();
switch(SelectMenu)
{
case 1:
showChoice();
break;
case 2:
add();
break;
case 3:
subtract();
break;
case 4:
multiply();
break;
case 5:
divide();
break;
case 6:
return false;
}
}
}