简体   繁体   English

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

[英]NumberFormatException when trying to compile a simple java program

This is my code: 这是我的代码:

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

Every time I run it, this is my output: 每次运行它时,这就是我的输出:

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)

I am confused as to why this NumberFormatException occurred; 我对为什么发生NumberFormatException感到困惑; could anyone explain why? 谁能解释为什么?

You are passing null to Integer.parseInt() . 您正在将null传递给Integer.parseInt() This means that br1.readLine() is returning null . 这意味着br1.readLine()返回null The only way this happens is if the end of stream has been reached. 发生这种情况的唯一方法是是否已到达流的末尾。 This means that you have somehow managed to not initialise System.in properly. 这意味着您已经设法以某种方式无法正确初始化System.in Try running the program from the command line with java RetailMarket in the same directory as the compiled class. 尝试使用java RetailMarket在与已编译类相同的目录中运行该程序。 This code works fine when I run it. 当我运行它时,此代码工作正常。

Also, you should consider catching NumberFormatException and keep the program running if the input is invalid eg 另外,您应该考虑捕获NumberFormatException并在输入无效的情况下保持程序运行,例如

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

You'll get that exception if br1.readLine() cannot be parsed as an int. 如果br1.readLine()无法解析为int,则会br1.readLine()该异常。 You should either validate that this String contains only digits, or you should catch the exception. 您应该验证此字符串仅包含数字,还是应该捕获异常。

No need to use BufferedReader, use a Scanner and read the Integer direcly without having to parse. 无需使用BufferedReader,使用Scanner并直接读取Integer,而无需进行解析。

Try this : 尝试这个 :

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM