无法将数组中的字符串分配给int

时间:2011-12-15 03:20:20

标签: java

我编写了以下代码行,用于读取文本文件中的数据并将其存储在数组中。除了我尝试将String转换为int时,一切正常。

这里我试图逐行扫描文本文件并将每个用逗号分隔的单词存储在一个数组中。当我将NumberFormatException转换为String并将其分配给int时,我无法弄清楚为什么会抛出int id

以下是我写的代码:

public boolean loadPapers(){
    String fileName = "paper.txt"; // file to be opened
    boolean fileOpened = true;
    int id, rank;
    String topic, author, date;

    try {
        Scanner fileData = new Scanner(new File(fileName));

        while(fileData.hasNextLine()){
            String line = fileData.nextLine();

            String[] words = line.split(","); // Separate words from sentence


            // get required parameters for Paper object
            id = Integer.parseInt(words[0]);  // throws numberFormatException
            topic = words[1];
            author = words[2];
            date = words[3];
            rank = Integer.parseInt(words[4]);  // throws numberFormatException

            // create new paper
            Paper entry = new Paper(id, topic, author, date, rank);
            paperList.add(entry);

        } // end while

        fileData.close(); // close file
    }  // end try

    catch (FileNotFoundException e) {
        fileOpened = false;
        swingErrorMessage("ERROR: File couldn't be opened.\nNo papers were loaded.", "File Error");
    } // end catch

    return fileOpened;

} // end loadPapers

以下是文本文件的内容:

46,Evolutionary Comp,Michael Smith,12/01/10,4
61,Fuzzy Logic and App,John Peterson,13/01/10,3
118,Neural Networks,Arthur London,20/01/10,5 
200,Evolutionary Comp,Scott Jones,30/01/10,1 
210,Fuzzy Logic and App,Joe Wang,01/02/10,4 
12,Evolutionary Comp,Andy Roberts,12/12/12,3 
123,Computer Science,Zhou You,12/12/12,3

程序失败的行是:

id = Integer.parseInt(words[0]);  // throws numberFormatException

错误消息如下:

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:470)
at java.lang.Integer.parseInt(Integer.java:499)
at PaperManagerApplication.Frame.loadPapers(Frame.java:409)
at PaperManagerApplication.PaperManager.main(PaperManager.java:16)

4 个答案:

答案 0 :(得分:2)

为什么不打印数组单词以查看拆分的作用?此外,请注意String中的空格 - 您通常应在trim()之前致电parseInt()

查看刚添加的堆栈跟踪,它会在空String上进行调整。添加System.out.println(line)以查看导致问题的行。

答案 1 :(得分:2)

您的数据不干净,请先修剪它。

答案 2 :(得分:2)

你可以只执行一个语句,删除除数字以外的所有字符:

word[4]= word[4].replaceAll( "[^\\d]", "" ); avoid all the non-digits chars.
Integer.parseInt(word[4]);

答案 3 :(得分:1)

关键在于:NumberFormatException: For input string: ""

你遇到的问题是输入中有一个空行,例如

123,Computer Science,Zhou You,12/12/12,3
<empty line here just before end of file>

或者您有一个空参数,例如

,Computer Science,Zhou You,12/12/12,3

实际上,您的代码没有问题,只是它没有处理上述两种情况。