尝试编译简单的java程序时出现NumberFormatException

时间:2014-08-03 16:33:46

标签: java exception numberformatexception

这是我的代码:

public class RetailMarket {
    public static void main(String[] args) throws IOException {
        int i,ch1,ch2,type,total=0,kg=0;
        System.out.println("What would you like to buy::");
        System.out.println("(1)Grains  (2)Oil");
        BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
        ch1 = Integer.parseInt(br1.readLine()); // exception thrown here
    }
}

每次运行时,这都是我的输出:

What would you like to buy::
(1)Grains  (2)Oil
Exception in thread "main" java.lang.NumberFormatException: null
    at java.lang.Integer.parseInt(Integer.java:454)
    at java.lang.Integer.parseInt(Integer.java:527)
    at RetailMarket.main(RetailMarket.java:16)

我很困惑为什么会发生这种NumberFormatException;谁能解释为什么?

3 个答案:

答案 0 :(得分:1)

您正在将null传递给Integer.parseInt()。这意味着br1.readLine()正在返回null。仅发生 的方式是,如果已到达流的末尾。这意味着您已经设法无法正确初始化System.in。尝试在命令行中使用java RetailMarket在与编译类相同的目录中运行程序。这个代码在我运行时工作正常。

此外,如果输入无效,您应该考虑捕获NumberFormatException并保持程序运行,例如

try {
    ch1 = Integer.parseInt(br1.readLine());
} catch (NumberFormatException e) {
    // invalid input
}

答案 1 :(得分:0)

如果br1.readLine()无法解析为int,您将获得该异常。 您应该验证此String仅包含数字,或者您应该捕获异常。

答案 2 :(得分:0)

无需使用BufferedReader,使用扫描仪并直接读取整数而无需解析。

试试这个:

 public class RetailMarket{

 public static void main(String[] args) throws IOException {
 int i,ch1,ch2,type,total=0,kg=0;
 System.out.println("What would you like to buy::");
 System.out.println("(1)Grains  (2)Oil");
 Scanner sc = new Scanner(System.in); 
 ch1 = sc.nextInt();
      }
   }