进行用户输入并检查用户是否输入String或int ...需要 如果用户输入字符串请求再次输入整数
while(menu!=5)
{
System.out.println("\nWelcome To Stavan Shah's Handy Calculator");
System.out.println("\n 1. Addition");
System.out.println("\n 2. Subtraction");
System.out.println("\n 3. Multiplication");
System.out.println("\n 4. Division");
System.out.println("\n 5. Exit");
Scanner sc = new Scanner(System.in);
System.out.println("\nWhat Would you Like To Do :- ");
c = sc.nextInt();
switch(c)
}
public static void pauseprog(){
System.out.println("Press Enter Key To Continue...");
Scanner sc = new Scanner(System.in);
sc.nextLine();
}
}
答案 0 :(得分:0)
你可以使用这样的东西
try {
Integer.parseInt(userInput);
} catch(NumberFormatException e) {
return false;
}
答案 1 :(得分:0)
这里只接受1-5:
之间输入的代码import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
void checkInput() {
Scanner s = new Scanner(System.in);
Pattern p = Pattern.compile("^[1-5]$"); // only one digit between 1-5
Matcher m;
boolean match = false;
while (!match){
System.out.print("Enter a number between 1 and 5: ");
m = p.matcher(s.next());
if(m.find()){
match = true;
int input = m.group(0);
// switch...
}
}
}