我正在尝试解析字符串表达式(即“6+10*2-5”)并使用 for-case 语句将答案计算为双精度。但是我收到了错误:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:470)
at java.lang.Integer.parseInt(Integer.java:499)
at Calculator.random(Calculator.java:50)
at Calculator.main(Calculator.java:210)
有任何想法吗?
public static double random(String exp) {
double primeResult = 0;
for (int i=0; i<exp.length();i++) {
double left = Integer.parseInt(exp.substring(0,i));
double right = Integer.parseInt(exp.substring(i+1,i+2));
switch(exp.charAt(i)) {
case '*':
primeResult = left * right;
break;
case '/':
primeResult = left / right;
break;
case '+':
primeResult = left + right;
break;
case '-':
primeResult = left - right;
break;
default:
return 0;
}
System.out.println(primeResult);
}
return primeResult;
}
}