I am trying to use stringTokenizer method for reading a 2D array stored in a file in the format..
1 1
1 1
the code is…
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for(int i=0;i<n;i++)
for(int j=0;j<n;j++){
StringTokenizer tok = new StringTokenizer(in.readLine());
t[i][j]=Integer.parseInt(tok.nextToken());
}
when i run this i am getting the java.lang.NullPointerException error.However if i use this in file
1 1 1 1
the code works!
why is it happening?
By having your
StringTokenizerobject declaration/instantiation in the nestedforloop theStringTokenizerobject doesn’t exist outside of the scope of the nested loop. So what this really does is just repeat the nested loop and so everything you read is horizontal only. If you move theStringTokenizeroutside of the nested loop and inside of the parent loop it will still be in scope for the nested loop. That should fix your problem.Move:
StringTokenizer tok = new StringTokenizer(in.readLine());above your nested loop.