簡體   English   中英

嘗試編譯簡單的Java程序時出現NumberFormatException

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

這是我的代碼:

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感到困惑; 誰能解釋為什么?

您正在將null傳遞給Integer.parseInt() 這意味着br1.readLine()返回null 發生這種情況的唯一方法是是否已到達流的末尾。 這意味着您已經設法以某種方式無法正確初始化System.in 嘗試使用java RetailMarket在與已編譯類相同的目錄中運行該程序。 當我運行它時,此代碼工作正常。

另外,您應該考慮捕獲NumberFormatException並在輸入無效的情況下保持程序運行,例如

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

如果br1.readLine()無法解析為int,則會br1.readLine()該異常。 您應該驗證此字符串僅包含數字,還是應該捕獲異常。

無需使用BufferedReader,使用Scanner並直接讀取Integer,而無需進行解析。

嘗試這個 :

 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