1

I am getting a nullPointerException trying to add values from a text file to a 2d array. The first 2 values determine the rows and columns. Any ideas what is throwing it. Ignore the exception handling, and the print statements. I am trying to get the array initialized then will go back and beef it up a bit.

public Help(String filename) throws FileNotFoundException,
        InvalidFileFormatException {
    this.filename = filename;

    System.out.println("Reading in file: " + filename);

    String number = "";
    int row = 0;
    int col = 0;
    int count = 0;

    try {
        Scanner inputFile = new Scanner(new File(filename));

        while (inputFile.hasNextInt()) {
            row = Integer.parseInt(inputFile.next());
            col = Integer.parseInt(inputFile.next());
            System.out.println("Row : " + row);
            System.out.println("Col : " + col);
            baseMap = new double[row][col];
            System.out.println(baseMap[2][4]);
            for (int i = 0; i < baseMap.length; i++){
                for (int j = 0; j < baseMap[i].length; j++){
                    baseMap[i][j] = Double.parseDouble(inputFile.next());
                }
            }
        }
System.out.println(baseMap[2][4]);
    } catch (Exception e) {
        System.out.println(e.toString());
    } 

OUTPUT Reading in file: sampleMap2.txt Row : 5 Col : 5 0.0 Exception in thread "main" java.lang.NullPointerException

3
  • 1
    Please add complete stacktrace please. Commented Sep 9, 2013 at 7:54
  • 1
    Which like is throwing the error? Commented Sep 9, 2013 at 7:56
  • For starters, use Scanner#nextInt instead of calling Integer#parseInt yourself; it's more readable, and you'll get a more informative exception if it fails. Commented Sep 9, 2013 at 8:29

1 Answer 1

2

What value do you expect to see here;

baseMap = new double[row][col];
System.out.println(baseMap[2][4]);

How about if row == 1?

Also what if there is no more data at:

baseMap[i][j] = Double.parseDouble(inputFile.next());

Maybe you just don't have enough data.

Sign up to request clarification or add additional context in comments.

3 Comments

I was just seeing if it actually initialized a 0.0 at that position. It prints out 0.0 before throwing the exception.
so what line is throwing the exception?
It was a different method in a different class that was throwing the exception. I am terribly sorry for wasting your time, but do appreciate your help. It got me thinking and helped me find the fix.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.