【发布时间】:2019-10-12 20:51:56
【问题描述】:
我有一个问题,我该如何做才能忽略所有非数字 int 的输入。
例如:
选项 1(添加) “输入两个整数:” 输入:asdf(
我相信这个验证将在 case switch 内完成,我在谷歌上搜索了一些关于解析和异常的信息,但它们并没有完全切入我正在寻找的内容。
欢迎提出建议、提示和批评。
提前致谢!
public class MathTeacher {
public static int addNumbers(int n1, int n2){
int add = n1+n2;
return add;
}
public static int subtractNumbers(int n1, int n2){
int subs = n1-n2;
return subs;
}
public static int multiplyNumbers(int n1, int n2){
int mulp = n1*n2;
return mulp;
}
public static int divideNumbers(int n1, int n2){
int div = n1/n2;
return div;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(true) {
int choices;
System.out.println(
"Welcome to *Mental Math Practice* where you can test your addition, subtraction, multiplication, and division.");
System.out.println("Enter 1 to add the two numbers.");
System.out.println("Enter 2 to subtract the second number from the first number.");
System.out.println("Enter 3 to multiply the two numbers.");
System.out.println("Enter 4 to divide the first number by the second number.");
choices = scanner.nextInt();
switch(choices){
case 1: {
System.out.println("Enter two integers: ");
int n1 = scanner.nextInt();
int n2 = scanner.nextInt();
int add = addNumbers(n1,n2);
System.out.println(add);
continue;
}
case 2: {
System.out.println("Enter two integers: ");
int n1 = scanner.nextInt();
int n2 = scanner.nextInt();
int sub = subtractNumbers(n1,n2);
System.out.println(sub);
continue;
}
case 3: {
System.out.println("Enter two integers: ");
int n1 = scanner.nextInt();
int n2 = scanner.nextInt();
int mulp = multiplyNumbers(n1,n2);
System.out.println(mulp);
continue;
}
case 4: {
System.out.println("Enter two integers: ");
int n1 = scanner.nextInt();
int n2 = scanner.nextInt();
int div = divideNumbers(n1,n2);
System.out.println(div);
continue;
}
}
System.out.println("Enter 'Quit' to end the program.");
}
}
}
【问题讨论】:
-
您可以简单地调用
scanner.nextLine()并忽略它,永久跳过该行。 (你不必使用它你知道)
标签: java string validation input int