Ton*_*ony 8 java exception-handling exception try-catch java.util.scanner
有人可以给我一个提示,为什么这个尝试和捕获不起作用?它会抛出扫描程序异常,而不是打印我期望的消息.
import java.util.*;
import java.io.*;
import java.math.*;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
Boolean test = true;
while (test == true) {
try {
double x, y;
String operator;
Scanner scan = new Scanner(System.in);
Scanner scan_2 = new Scanner(System.in);
Scanner ScanOperator = new Scanner(System.in);
System.out.println(" Enter a double value: ");
x = scan.nextDouble();
System.out.println(" Enter another double value: ");
y = scan_2.nextDouble();
System.out.println(" Enter a operator for the operation you want to execute, or X if you want to quit: ");
operator = ScanOperator.nextLine();
if (operator.equals("x") || operator.equals("X")) {
test = false;
System.out.println("No calculation was made!!!");
}
System.out.println(Calculation(operator, x, y));
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null,"Input must be a number.");
}
}
}
public static double Calculation(String operator, double x, double y) {
double result = 0;
double myAdd = 0;
double mySub = 0;
double myMult = 0;
double myDiv = 0;
double myPower = 0;
double myMod = 0;
if (operator.equals("+")) {
myAdd = x + y;
result = myAdd;
} else if (operator.equals("-")) {
mySub = x - y;
result = mySub;
} else if (operator.equals("*")) {
myMult = x * y;
result = myMult;
} else if (operator.equals("/")) {
myDiv = x / y;
result = myDiv;
} else if (operator.equals("^")) {
myPower = Math.pow(x, y);
result = myPower;
} else if (operator.equals("%")) {
myMod = x % y;
result = myMod;
} else {
}
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
zmb*_*ush 21
很简单,程序抛出ScannerException,但是你的try catch只能捕获NumberFormatException,你需要添加另一个catch子句以捕获ScannerException,或者只捕获一般的Exception.
例如,当你说:
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null,"Input must be a number.");
}
Run Code Online (Sandbox Code Playgroud)
这只是指定如何捕获NumberFormatException.
为了捕获所有异常,您需要进行以下操作:
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null,"Input must be a number.");
}catch (Exception e){
JOptionPane.showMessageDialog(null,"Generic exception caught");
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,第二个catch将获取第一个catch中未捕获的所有内容,因为所有异常都扩展了Exception类,您可以使用该语句捕获所有派生类.
但是,由于自身捕获异常是不受欢迎的,您还可以这样做:
} catch (NumberFormatException, ScannerException e) {
JOptionPane.showMessageDialog(null,"Input must be a number.");
}
Run Code Online (Sandbox Code Playgroud)
在同一个块中捕获两个异常.