簡體   English   中英

Integer.parseInt() 拋出 NumberFormatException

[英]NumberFormatException being thrown by Integer.parseInt()

對於我的作業,我試圖將一系列整數讀入一個數組並計算有關該數組的一些內容。 我只能使用 InputStreamReader 和 BufferedReader 從文件中讀取,並且 Integer.parseInt() 在讀取第一行后拋出 NumberFormatException。

如果我通過鍵盤單獨輸入每個數字,一切都正常,但如果我嘗試直接從文件中讀取,則根本不起作用。

這是到目前為止的代碼

int[] array = new int[20];

    try {
        int x, count = 0;
        do{
            x = Integer.parseInt((new BufferedReader(new InputStreamReader(System.in)).readLine()));
            array[count] = x;
            count++;
        }
        while (x != 0);
    }
    catch (IOException e){
        System.out.println(e);
    }
    catch (NumberFormatException e){
        System.out.println(e);
    }

要測試的案例是

33
-55
-44
12312
2778
-3
-2
53211
-1
44
0

當我嘗試復制/粘貼整個測試用例時,程序只讀取第一行,然后拋出 NumberFormatException。 為什么 readLine() 只讀取第一個值而忽略其他所有內容?

您每次都重新打開System.in 我不知道這有什么作用,但我認為它不會很好。

相反,您應該使用一個BufferedReader ,並在您的循環中,從中一一讀取行。

我認為發生這種情況的方式是您創建一個閱讀器,讀取一行,然后在下一次迭代中創建一個新的,它是空的但仍然嘗試讀取,因此它讀取“”,將其傳遞給parser 和Integer.parseInt()拋出 NumberFormatException 因為它無法被解析。 正確的做法是:

int[] array = new int[20];

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
        int x, count = 0;
        do {
            String s = reader.readLine();
            x = Integer.parseInt(s);
            array[count] = x;
            count++;
        }
        while (x != 0);
    } catch (IOException | NumberFormatException e) {
        e.printStackTrace();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM