2

Not sure why this is getting a NullPointerException.

According to error log, NullPointerException is thrown while executing this statement. "file[i] = loadSaveFile.nextLine()" towards the end of the script.

public class SaveGame {
static String[] file;
static String loadSaveFile;
static String gameDir;
static int numLines = 0;

public static void main(String[] args) throws FileNotFoundException {
    File saveFile = new File(gameDir + "\\savefile.txt");
    Scanner loadSaveFile = new Scanner(saveFile);
    Scanner findNumLines = new Scanner(saveFile);
    while(findNumLines.hasNext() != false){
        findNumLines.nextLine();
        numLines++;
    }
    for (int i = 0; i < numLines; i++) {
        file[i] = loadSaveFile.nextLine();
        if(loadSaveFile.hasNextLine() == false){
            break;
        }
    }
}
}
Ajay P. Prajapati
  • 1,973
  • 1
  • 17
  • 34

1 Answers1

1

At no point are you setting the value of the array SaveGame.file itself, so it is defaulting to null. You need to do something like

file = new String[numLines];

between the while loop and the for loop.

Jonathan Callen
  • 11,301
  • 2
  • 23
  • 44
  • Woah I don't quite understand why but it worked. Thanks! Gonna spend a few minutes trying to learn what I did wrong, though. – AnExoticllama Jun 28 '15 at 23:38