0

Solved

The first line of the text file in the array is the number of students. I need to scan this number, make my array the size of the number, and then print out each line of students and their corresponding information from the text file.

I've reviewed the logic several times and can't seem to find what could be wrong with it. I can compile the method but when I run it I get a null pointer exception, which means I must be doing something wrong when assigning the array to the students information.

My code right now is:

import java.io.*;
import java.util.Scanner;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) throws IOException {

        Chart();
    }

    public static void Chart() throws IOException {
        int n;
        Scanner fileScan;
        fileScan = new Scanner(new File("scores.txt"));
        n = fileScan.nextInt();
        String[] students = new String[n];
        for (int i = 0; i > n; i++) {
            students[i] = fileScan.nextLine();
        }
        Arrays.sort(students);
        for (int i = 1; i > n; i++) {
            System.out.println(students[i]);
        }
    }
}

Am I doing everything right reading the lines in the text file into the array? If so what is causing the error?

3
  • 2
    Which line is throwing the exception? Commented Apr 21, 2014 at 2:10
  • 1
    int i = 0; i > n; i++ You might be wanting <. Commented Apr 21, 2014 at 2:11
  • @VTedd why don't you add the solution to an answer, so if this comes up later, people will know what you did to solve it. After 48 hours you should probably mark your answer as the correct one, if it is the correct one. Or if someone else posted the correct answer, could you mark it correct? Commented Apr 21, 2014 at 2:43

2 Answers 2

4
for(int i = 0; i > n; i++) {
     students[i] = fileScan.nextLine();
}

This loop is not inserting values to the array.

It must be,

for(int i = 0; i < n; i++) {
     students[i] = fileScan.nextLine();
}
Sign up to request clarification or add additional context in comments.

1 Comment

I am facepalming so hard right now. I can't believe the reason it messed up is because I had my signs wrong. I'm sorry for wasting everyone's time, works fine now.
2

It's hard to know for sure without your stacktrace (which would point to which line has the null reference) - but both of your loop conditions are incorrect:

for(int i = 0; i > n; i++)

Your loop block is never going to run with that check.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.