NumberFormatException:对于输入字符串:“ AM” Java

时间:2019-11-25 16:07:22

标签: java arrays filereader numberformatexception

如何创建一个for循环,该循环生成从文本文件读取值的不同对象? 我的文本文件:


1, Title1, 1
AM, AP
9, 8, 7
2, Title2, 2
AM, PS, TC
10, 8
3, Title3, 3
AM, PP
1, 2, 4
4, Title4, 2
JD
6

2 个答案:

答案 0 :(得分:0)

引起问题的是在while循环中使用的readLine()方法,该方法将指针向前移动了一行(到包含1, Title1, 1的第一行)。

第二次在for循环本身的第一行中调用readLine(),现在将光标移至第二行(即AM, AP

希望您知道错误从何而来。

我可以建议您移动循环的第一行吗?

        for (int i=0; i<N; i++){
            line= br.readLine();    //this line
            String[] tokens = line.split(",");

到最后

            collection.addPaper(objectX); //adding object into the collection
            line= br.readLine();      //move it here
        }
        System.out.println("Worked");

希望您能理解我的建议以及原因!

我记得,FileReader跳过空行。 (仅包含\ n)

或者,删除while循环本身也可以解决。

答案 1 :(得分:0)

您应该在代码中解决以下问题:

  1. 删除没有意义的for循环。
  2. 使用泛型引用实例,例如List<String> author = new ArrayList<String>();代替ArrayList<String> author = new ArrayList<String>();
  3. 每当您从文件中读取一行或将读取的行拆分为一个数组时,请检查null
  4. 修剪拆分的String值,然后将其解析为int
  5. 语句paperTitle = tokens[2]; //Storing second value应该为paperTitle = tokens[1];

以下是结合了上述所有要点的代码:

try {
    File file = new File("C:\\Users\\hi123\\Desktop\\input1.txt");
    br = new BufferedReader(new FileReader(file));
    String line;

    int paperId;
    String paperTitle;
    int quartile;
    List<String> author = new ArrayList<String>();
    List<Integer> scoreReview = new ArrayList<Integer>();

    while ((line = br.readLine()) != null) {

        String[] tokens = line.split(",");

        paperId = Integer.parseInt(tokens[0].trim()); //First value in the array
        paperTitle = tokens[1].trim(); //Second value in the array
        quartile = Integer.parseInt(tokens[2].trim()); //Third value in the array

        line = br.readLine(); //Read next line
        String[] tokensAuthor;
        if ((line = br.readLine()) != null) {
            tokensAuthor = line.split(",");
        }
        if (tokensAuthor != null) {
            for (int j = 0; j < tokensAuthor.length; j++) {
                author.add(tokensAuthor[j].trim()); 
            }
        }

        line = br.readLine(); //Read next line
        String[] tokensInt;
        if ((line = br.readLine()) != null) {
            tokensInt = line.split(",");
        }
        if (tokensInt != null) {
            for (int j = 0; j < tokensInt.length; j++) {
                scoreReview.add(Integer.parseInt(tokensInt[j].trim()));
            }
        }
        PaperCollection collection = new PaperCollection();
        Paper objectX = new Paper(paperId, paperTitle, quartile, author, scoreReview);
        collection.addPaper(objectX); // adding object into the collection
    }
    System.out.println("Worked");
} catch (Exception e) {
    e.printStackTrace();
}