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 :)
NullPointerException.planets[i]planetsis refering to 8nullvalues. so you need to initialize it before you callcharAt()