簡體   English   中英

為什么Integer.parseInt在看似有效的輸入上拋出NumberFormatException?

[英]Why does the Integer.parseInt throw NumberFormatException on input that seems valid?

我正在從書中做一個簡單的練習,我對java函數parseInt的工作原理有點困惑。 我從輸入文件中讀取了一行,使用StringTokenizer將其拆分,現在我想將每個部分解析為整數。

我在監視窗口中檢查了parseInt函數的輸入確實是一個看似有效整數的字符串(例如“35”)。 但是,當我嘗試在我的變量str上使用str.charAt函數保持值“35”時,我得到奇怪的結果:

str.charAt(0) == ""
str.charAt(1) == "3"
str.charAt(2) == ""
str.charAt(3) == "5"

這似乎是一個可能與編碼有關的問題,因此我嘗試使用這種方式讀取文件來修復它:

InputStreamReader reader = new InputStreamReader(new FileInputStream(inputfile), "UTF-8");

(我在編輯器中使用UTF-8編碼明確保存了文件),但這沒有用。 任何想法可能是什么問題以及如何解決它?

編輯:我的樣本

        InputStreamReader reader = new InputStreamReader(new FileInputStream(inputfile), "UTF-8");
        BufferedReader bfreader = new BufferedReader(reader);

        line = bfreader.readLine();
        while (line !=null)
        {
                String[] valueStrings = line.split(" ");
                String hole = valueStrings[0]; 

                int[] values = new int[4];
                for (int i = 0; i <values.length; i++){

                    String nr = valueStrings[i+1].trim(); 
                    values [i] = Integer.parseInt(nr);
                }

                // it breaks at the parseInt here, the rest is not even executed...

         }

我的猜測是它實際上是

str.charAt(0) == '\0'
str.charAt(1) == '3'
str.charAt(2) == '\0'
str.charAt(3) == '5'

聽起來它可能實際上是以UTF-16而不是UTF-8保存 - 但如果你的文本編輯器認為它是為了保存“空”字符,那就沒有意義。 嘗試在二進制十六進制編輯器中查看文本文件 - 我懷疑你會發現每隔一個字節都是0。

如果這沒有幫助,請發一個簡短但完整的程序來演示問題 - 到目前為止我們只看到了一行代碼。

暫無
暫無

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

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