java.lang.NumberFormatException : For input string: "" parsing string expression 异常

标签 java for-loop case

我正在尝试解析字符串表达式(即“6+10*2-5”)并使用 for-case 语句将答案计算为 double 值。但是我收到错误:

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;
    }
}

最佳答案

您的问题与switch/case无关。问题很简单,您正试图将一个空字符串解析为一个数字。找出为什么你有一个空字符串,然后修复它。 (提示:您希望 exp.substring(0, 0) 返回什么?)

您还应该考虑当 iexp.length() 时您期望 exp.substring(i+1,i+2) 返回什么 - 1(甚至 exp.length() - 2)。

此外,退后一步,考虑为什么您认为这是 switch/case 部分的问题。查看堆栈跟踪 - 它甚至不在 switch/case 语句中,而是在它之前。能够诊断实际发生错误的位置非常重要,这样您就可以专注于此,而不会被不相关的部分分心。

关于java.lang.NumberFormatException : For input string: "" parsing string expression 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16721552/

相关文章:

Python 多重嵌套三元表达式

python - Python 中的 Switch/Case 实现有什么值(value)吗?

c - 如果 switch 语句正在执行 C 中的所有其他情况,如何停止它?

javascript - 如何进行不区分大小写的文本输入?

java - Gin 辅助注入(inject) : Deferred binding result type 'Foo' should not be abstract

java - 使用@Async 嵌套@Transactional 方法

JavaScript 从 00000 循环到 000256

java - 如何使用hibernate在spring boot的fillAll方法中添加where条件

java - 使用 Iterator 从 HashMap 返回对象

java - 在java中打印中心对齐的三角形和倒置的三角形