我现在已经进入了try catch,程序仍然跳到第二个&第3个输入问题,不打印错误异常("输入你的操作:加,减,除,乘或退出")。如果"退出"是第二个问题的第一个问题。第三个输入要求在程序完成之前仍然循环,是否有任何方法可以立即退出,并且需要其他输入? 欢迎任何建议
import java.util.Scanner;
import java.io.*;
class Monday {
public static void main(String[] args) {
double n1,n2;
boolean check = true;
while(check) {
System.out.println("Enter your operation: add, subtract, divide, multiply, or exit");
Scanner myScan = new Scanner(System.in);
String op = myScan.next();
try {
System.out.println("Enter your 1st number");
try {
n1 = myScan.nextDouble();
System.out.println("Enter your 2nd number");
n2 = myScan.nextDouble();
} catch (Exception e) {
System.out.println("This is my error");
return;
}
/* System.out.println("Enter your 1st number");
n1 = myScan.nextDouble();
System.out.println("Enter your 2nd number");
n2 = myScan.nextDouble();*/
switch (op) {
case"add":
System.out.println("Your answer is "+ (n1 + n2));
break;
case"subtract":
System.out.println("Your answer is "+ (n1 - n2));
break;
case"divide":
System.out.println("Your answer is "+ (n1 / n2));
break;
case"multiply":
System.out.println("Your answer is "+ (n1 * n2)) ;
break;
case"exit":
System.out.println("Goodbye!");
break;
}
if ("exit".equals(op))
check = false;
} catch (Exception e) {
System.out.println("This is my error");
System.exit(1);
}
}
}
}
答案 0 :(得分:0)
你甚至不需要尝试/捕捉。
double n1, n2;
System.out.println("Enter your 1st number");
if (myScan.hasNextDouble()) n1 = myScan.nextDouble();
else return;
System.out.println("Enter your 2nd number");
if (myScan.hasNextDouble()) n2 = myScan.nextDouble();
else return;
但是如果你想使用它:
double n1, n2;
System.out.println("Enter your 1st number");
try {
n1 = myScan.nextDouble();
System.out.println("Enter your 2nd number");
n2 = myScan.nextDouble();
} catch (Exception e) {
System.out.println("This is my error");
return;
}