當用戶輸入以下任何一項時,應引發UnknownOperatorException + - */PR
但是,它似乎不能正常工作。這裏是一個示例輸出。UnkownOperatorException爲什麼不被拋出?
Enter an operator and a number:
+5
Enter an operator and a number:
g9
5.0
主類從未具體輸出消息,但該異常被拋出的方法確實...因此,如果異常被捕獲不應該被打印的信息?
這裏是我的主類:
public class Main{
public static void main (String[] args) throws Exception {
Calculator a = new Calculator(0);
a.setNumber(a.aResult(a));
a.setNumber(a.aResult(a));
String theString = String.valueOf(a.getNumber());
System.out.println(theString);
}
}
這是調用它拋出異常
public void whatOperator() throws Exception
{
String operatorString = null;
operatorString = enterNumber();
// shouldn't this test the string and throw the exception if needed?
throwOperatorException(operatorString);
if(operatorString.substring(1).equals(""))
{
switch(operatorString){
case "R":
result = RESET;
break;
case "P":
System.out.println("Goodbye");
System.exit(0);
}
}
else
theNumber = Double.parseDouble(operatorString.substring(1));
char theOperator = operatorString.charAt(0);
this.operator = theOperator;
operatorString ="";
operatorString += theOperator;
switch(operatorString){
case "*":
result = getNumber() * theNumber;
break;
case "/":
result = getNumber()/theNumber;
break;
case "+":
result = getNumber() + theNumber;
break;
case "-":
result = getNumber() - theNumber;
break;
}
}
最後例外方法本身的方式方法。不知何故,它不會被拋出。我認爲它與if語句嵌套在一起,但我不確定如何解決這個問題。
public void throwOperatorException(String entry) throws Exception
{
char oneOperator;
for(int i = 0; i < ALL_OPERATORS.length();i++)
{
oneOperator = ALL_OPERATORS.charAt(i);
if(entry.charAt(0) != oneOperator && i == ALL_OPERATORS.length())
{
try{
throw new UnkownOperatorException(entry);
}catch(UnkownOperatorException e){
System.out.println(e.getMessage());
}
}
}
}
這是ALL_OPERATORS
private final String ALL_OPERATORS = "+-*/RP";
這是有道理的。所以我只需要從長度中減去1 ...... – mark1092
@ mark1092應該可以工作,但除非您嘗試一下,否則無法保證。 – nullpointer