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?

有帮助吗?

解决方案

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();
}

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top