user1172026
user1172026

Reputation: 1

Getting a NullPointerException - how to remove it?

I'm new in programming.

array [row][col] = line.charAt(col);

^ this the line is where I'm getting NullPointerException in my code. How to remove it?

Scanner in = null;
try {
    in = new Scanner(new FileReader("C:\\Documents and Settings\\UserXP\\My Documents\\src\\file.txt"));
} catch (FileNotFoundException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}
String line="";
ArrayList<String>arrayList=new ArrayList<String>();

while((line=in.nextLine())!=null) {
    arrayList.add(line);
    char [][] array = new char [2337][];
    for (int row = 0; row<arrayList.size(); row++)
        for(int col = 0; col<line.length(); col++) {
            array [row][col] = line.charAt(col);
            System.out.print(""+ array[row][col]);
        }
    System.out.println("");
}

//Close the input stream
in.close();

Upvotes: 0

Views: 2689

Answers (1)

beny23
beny23

Reputation: 35018

You're never allocating any memory for the second dimension of your array:

char [][] array = new char [2337][];

Gives you 2337 char[]s but all of them are null.

You'll need

array[row] = new char[line.length()];

before the column loop.

EDIT (clarify where to insert):

for (int row = 0; row<arrayList.size(); row++) {
    array[row] = new char[line.length()];
    for(int col = 0; col<line.length(); col++) {
        array [row][col] = line.charAt(col);
        System.out.print(""+ array[row][col]);
    }
}

Note also, as your logic appears inefficient, as you're recreating rows every time you're adding a line.

Upvotes: 7

Related Questions