Null pointer access: The variable arrayLocations can only be null at this location

Chris Keli :

So I'm trying to read in a file and get parts from it, but i keep getting the above error at line

arrayLocations[i] = new Location(Double.parseDouble(xArray[1]), Double.parseDouble(xArray[2]))

    int total;
    BufferedReader bfr;
    String lineObtained = null;
    Location[] arrayLocations = null;

    try {

        bfr = Files.newBufferedReader(path);
        lineObtained = bfr.readLine();

    } catch (IOException e) {

        e.printStackTrace();
        return null;
    }

    String split = lineObtained.split("POSTAL_OFFICE")[1];
    String[] y = split.split(" ");
    double xCoord = Double.parseDouble(y[0].trim());
    double yCoord = Double.parseDouble(y[1].trim());
    Location postOffice = new Location(xCoord, yCoord);

    String split1 = lineObtained.split("WORKER_ADDRESS")[1];
    String[] y1 = split.split(" ");
    double xCoord1 = Double.parseDouble(y1[0].trim());
    double yCoord1 = Double.parseDouble(y1[1].trim());
    Location home = new Location(xCoord, yCoord);        

    split = lineObtained.split("POSTAL_ADDRESSES")[1].trim();
    String[] splits = split.split("\\r?\\n");

    for(int i = 0; i < splits.length; i++) {
        String[] xArray = splits[i].split(" ");
        arrayLocations[i] = new Location(Double.parseDouble(xArray[1]), Double.parseDouble(xArray[2]));
    }

    PWPInstance instance = new PWPInstance(total, arrayLocations, postOffice, home, random);
    return instance;
Federico klez Culloca :

You declared arrayLocation as null and never initialized it.

You probably want something like

Location[] arrayLocations = new Location[splits.length];

Just before the loop (no need to declare it at the beginning of the method, declare it when it's needed), since that's the first place you use it and the place you know how big the array needs to be.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=400592&siteId=1