0

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 :)

7
  • Well, your array is filled with null strings. There is no character at the first index - hence the NullPointerException. Commented Apr 4, 2017 at 18:40
  • There's nothing in planets[i] Commented Apr 4, 2017 at 18:40
  • planets is refering to 8 null values. so you need to initialize it before you call charAt() Commented Apr 4, 2017 at 18:40
  • Now it's a whole different story. You can't just remove lines from your program like that. Commented Apr 4, 2017 at 18:43
  • @Gendarme sorry about that! (new to the site) Commented Apr 4, 2017 at 18:47

1 Answer 1

1

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());
}
Sign up to request clarification or add additional context in comments.

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.