当用户输入除以下 +-*/PR 之一之外的任何内容时,应抛出 UnknownOperatorException
但是,它似乎无法正常运行。这是示例输出。
Enter an operator and a number:
+5
Enter an operator and a number:
g9
5.0
主类从不专门输出消息,但是抛出异常的方法会输出......所以如果捕获到异常,不应该打印消息吗?
这是我的主要类(class):
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";
最佳答案
自
i == ALL_OPERATORS.length()
永远不会是真的(或者总是假
),为什么?问问自己是否在内部循环
for(int i = 0; i < ALL_OPERATORS.length();i++)
这会发生吗?
<小时/>因此,您的 if
中的代码永远不会到达,因此永远不会抛出 UnkownOperatorException
。
检查String
条目的第一个字符是否是ALL_OPERATORS
之一的另一种方法是使用contains()
关于java - 为什么 UnkownOperatorException 没有被抛出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42662702/