java - StringTokenizer 无法与 BufferedReader 一起使用

标签 java bufferedreader stringtokenizer

我尝试将 StringTokenizer 与 BufferedReader 一起使用,但出现错误。 当我使用 Scanner 时它可以工作,但是当我更改为 BufferedReader 时我无法使其工作。我需要您的意见来了解我的代码有什么问题。这是我的源文件的样子:

Stud Qu1 Qu2 Qu3 Qu4 Qu5 
1234 052 007 100 078 034 
2134 090 036 090 077 030 
3124 100 045 020 090 070 
4532 011 017 081 032 077 
5678 020 012 045 078 034 
6134 034 080 055 078 045 
7874 060 100 056 078 078 
8026 070 010 066 078 056 
9893 034 009 077 078 020 
1947 045 040 088 078 055 
2877 055 050 099 078 080 
3189 022 070 100 078 077 
4602 089 050 091 078 060 
5405 011 011 000 078 010 
6999 000 098 089 078 020 

And this is the error I am getting:
Exception in thread "main" java.lang.NullPointerException
    at lab4.Student.<init>(Student.java:26)
    at StudentReportApp.main(StudentReportApp.java:6)

import lab4.*;

public class StudentReportApp {
    public static void main (String [] args){
        String fileName = "input.txt";
        Student studentData = new Student(fileName);
        //studentData.findReport ();
        //studentData.printReport ();
    }
}

public Student (String FileName){
        File file = new File(FileName);

        try (BufferedReader br = new BufferedReader(new FileReader(file))){
            String line;

            br.readLine(); //skips first line
            int r = 0;
            while ((line = br.readLine())!= null){
                StringTokenizer stToken = new StringTokenizer(line, " ");
                while(stToken.hasMoreTokens()){
                    student[r] = Integer.parseInt(stToken.nextToken());
                    for (int c = 1; c < 6; c++)
                        grade [r][c-1] = Integer.parseInt(stToken.nextToken());      
                    r++;
                }
                arrayStudents++;
            }

            student = new int [arrayStudents];
            grade = new int[arrayStudents][5];

        } catch (FileNotFoundException e) {
            System.out.println("Can't find file " + file.toString());
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("Unable to read file " + file.toString());
            e.printStackTrace();
        }
    }

最佳答案

grade [r][c-1] = Integer.parseInt(stToken.nextToken());      

在这段代码中,您尝试再次访问 nextToken..这将使标记生成器比当前位置向前移动一步。

相反,您应该首先检查该 token 是否可用,然后访问该 token 。

正确方法:

if(stToken.hasNextToken())
{
 grade[r][c-1] = Integer.parseInt(stToken.nextToken());   
 }

关于java - StringTokenizer 无法与 BufferedReader 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21972561/

相关文章:

java - 字符串分词器分离

java - 需要一种更好的方法从文本文件中读取和存储值

java - 简化代码以加载 XML 文件的建议?

java - Apache Flink(集群中的标准输出错误)

java - BufferedReader 和 BufferedInputStream 的区别

java - 如何在java中从bufferedreader读取并运行多个变量?

java - 将文件中的字符串值转换为整数

java - 使用堆栈在 java 中获取 infix/postfix 的错误输出

java - 为什么 String.split ("£", 2) 不工作?

java - 从另一个类运行 GUI?