数字格式异常错误逻辑帮助没有看到问题

时间:2015-04-14 18:12:10

标签: java object methods while-loop

尝试在我的表达式字符串中设计和退出命令时出现数字格式异常错误。建议将非常感激:)。

String expression = " ";
//all other varaible in loop are declared and intialized
//removed for cluttering purposes
while(!expression.equals("QUIT"))
        {
            expression = kbd.nextLine();
            variable = expression.charAt(0);
            startIndex = expression.lastIndexOf(" ")+1;//index of future integer value 
            StringLength = expression.length();
            strValue = expression.substring(startIndex,StringLength);
            intValue = Integer.parseInt(strValue);//ERROR HERE numberFormatException
        }
        System.out.println(" "+strValue);//STRING VALUE TEST PRINT
        tempIndex.put(variable,intValue);//assigns int value to variable
        int getVarValue = tempIndex.get(variable);//gets value stored in variable 
        System.out.println(variable+" = "+getVarValue);
 

1 个答案:

答案 0 :(得分:1)

Java抱怨你没有在这里给她一个整数:

intValue = Integer.parseInt(strValue);

例如,如果我只是运行

Integer.parseInt("1a");

我会收到一个错误,因为parseInt不会让它1,它会抛出这个异常,说它不知道在这种情况下该做什么,

您可以先尝试验证字符串,然后再尝试解析它。正则表达式在这里很方便。如果你不知道正则表达式,只需检查字符串中的所有字符是'0','1','2',......'9'。如果遇到其他问题,您就不要调用parseInt方法