-2

Here is my code to read a text file line per line.

    ArrayList<Student> studentCollection = new ArrayList<Student>();
    BufferedReader in = null;
    try {
        in = new BufferedReader(new FileReader("StudentAnswers2.txt"));
        String read = null;
        while ((read = in.readLine()) != null) 
        {
            read = in.readLine();
            String[] splited = read.split(",");
            int[] answersTrans = new int[20]; 
            for(int i = 0; i < 20; i++)
            {
                answersTrans[i] = Integer.parseInt(splited[i+3]); 
            }           
            studentCollection.add(new Student(splited[0], splited[1], splited[2], answersTrans));                  
        }

Context: I am trying to set each comma separated value as fields of a List of Student objects ( one line per Student). The first 3 values need to go in as String parameters, and the following 20 values go in as one int[] array.

Here's the content of the txt file:

C97288501,Byrne,John,0,3,3,0,2,4,0,1,4,5,0,3,3,1,2,4,2,0,4,5 D11255403,Smith,Eileen,1,3,2,0,4,3,1,4,5,0,3,3,1,3,4,5,0,5,4,0 C06623662,Doyle,Mary,1,4,3,3,2,2,1,1,4,5,3,3,3,5,2,4,2,5,4,5 C02887223,Radecki,Jason,2,4,3,0,2,2,4,1,0,2,3,3,5,0,4,4,0,4,0,5 D11123581,Hanley,Nora,1,0,2,2,3,0,0,1,5,4,3,3,0,3,2,4,0,5,4,4

singhakash
  • 7,891
  • 6
  • 31
  • 65
full_prog_full
  • 1,139
  • 10
  • 17
  • I am not sure if this is exactly a duplicate. The OP is asking why it is being thrown, not what a NPE is. They just don't know why it would be thrown when something is in the file. See @Eran answer – Ascalonian Mar 11 '15 at 12:23
  • 1
    Thanks, I removed the extra in.readLine() and it works now :) – full_prog_full Mar 11 '15 at 12:25
  • You should thank @Eran by giving an upvote and accept his answer (if possible) :-) – Ascalonian Mar 11 '15 at 12:30

1 Answers1

3

Remove the extra in.readLine(), since you already read the line in the condition of the while loop. the extra in.readLine() causes you to skip every second line, and may cause the following read.split(",") to throw NullPointerException, since you don't check if it returned null.

    while ((read = in.readLine()) != null) 
    {
        read = in.readLine(); // this extra readLine is wrong
                              // and should be removed
Eran
  • 387,369
  • 54
  • 702
  • 768