Null Pointer Exception Error When Printing Array of Strings from a Text File in Java

StackOverflow https://stackoverflow.com/questions/23189791

  •  06-07-2023
  •  | 
  •  

Вопрос

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