Aparna
Aparna

Reputation: 1

Using String Array and Printfile Output getting NullPointerException?

So, I'm writing a program in which I need to have a loop that "reads and writes the first character of the strings stored in each element of the array to the output file".

I keep getting a NullPointerException at: a = planets[i].charAt(0);

 String[] planets = new String[8];
    char a = 'a';

    String pl = "planets.txt";
    File file = new File(pl);
    Scanner inputFile = new Scanner(file);

    for(int i = 0; i < planets.length; i++){
        while(inputFile.hasNext()){
            planets[i] = inputFile.nextLine();
        }
    }
    inputFile.close();

    System.out.println("closed.");

    String b = "planetfirst.txt";
    PrintWriter outputFile = new PrintWriter(b);

    for (int i = 0; i< planets.length; i++){

        a = planets[i].charAt(0);

        outputFile.println(a);
    }


    outputFile.close();
    System.out.println("Data written to the file.");

Thanks in advance!

edit: I added the rest of my program for some context :)

Upvotes: 0

Views: 32

Answers (1)

RaminS
RaminS

Reputation: 2239

Your while loop is inside your for loop, so all the text will be inside planets[0], and the rest of the indices will be empty (i.e null). When you later iterate through the array with

for(int i = 0; i < planets.length; i++) {
    a = planets[i].charAt(0);
}

you will get a NullPointerException when i is larger than 0.

If your textfile has 8 lines, then there is no need for the while-loop, because you have a for loop that iterates 8 times, and an array of length 8.

If the number of lines in your textfile varies, however, you shouldn't use an array, and instead use an arraylist, and instead of a for loop, only have your while loop.

Something like

List<String> planets = new ArrayList<String>();
while(inputFile.hasNext()){
    planets.add(inputFile.nextLine());
}

Upvotes: 1

Related Questions