I am trying to write a program that reads a txt file and prints out its 2d numbers only array, but i got NullPointerEexception I have no idea why, please help
Here is my code:
import java.io.*;
import java.util.*;
public class FileR {
public static void main(String[] args) throws Exception {
int[][] desktop;
int rows = getTotalRow();
desktop = new int[rows][];
Scanner fin;
InputStream is;
is = new FileInputStream("hello.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = "";
try {
int row = 0;
while ((line = br.readLine()) != null) {
line = line.replaceAll("[^0-9]+", "");
if (line.isEmpty())
continue;
String[] nums = line.split("\\s*(|,|\\s)\\s*");
desktop[row] = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
desktop[row][i] = Integer.parseInt(nums[i]);
}
row++;
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
print(desktop);
}
public static int getTotalRow() throws IOException {
LineNumberReader reader = null;
try {
reader = new LineNumberReader(new FileReader("hello.txt"));
while ((reader.readLine()) != null) ;
return reader.getLineNumber();
} catch (Exception ex) {
return -1;
} finally {
if (reader != null)
reader.close();
}
}
public static void print(int[][] value) {
for (int i = 0; i < value.length; i++) {
for (int j = 0; j < value[i].length; j++) {
System.out.print(value[i][j] + " ");
}
System.out.println();
}
}
}
HEre is my hello txt file:
There should be a specific text at the top of each page
2 2, 2, 2, 2, 2, 2, 2, 2, 2
2, 0, 0, 0, 0, 0, 0, 0, 0, 2
2, 0, 0, 0, 0, 0, 0, 0, 0, 2
2, 0, 0, 0, 0, 0, 0, 0, 0, 2
2, 0, 0, 1, 3, 4, 0, 0, 0, 2
2, 0, 0, 0, 3, 4, 0, 0, 0, 2
2, 0, 0, 0, 0, 0, 0, 0, 0, 2
2, 0, 0, 0, 0, 0, 0, 0, 0, 2
2, 0, 0, 0, 0, 0, 0, 0, 0, 2
2, 2, 2, 2, 2, 2, 2, 2, 2, 2
lmlmlm
my ouput :
2 2 2 2 2 2 2 2 2 2
2 0 0 0 0 0 0 0 0 2
2 0 0 0 0 0 0 0 0 2
2 0 0 0 0 0 0 0 0 2
2 0 0 1 3 4 0 0 0 2
2 0 0 0 3 4 0 0 0 2
2 0 0 0 0 0 0 0 0 2
2 0 0 0 0 0 0 0 0 2
2 0 0 0 0 0 0 0 0 2
2 2 2 2 2 2 2 2 2 2
Exception in thread "main" java.lang.NullPointerException
at FileR.print(FileR.java:55)
at FileR.main(FileR.java:34)
I guess NullPointerException caught when it loops empty string or null object, i want to omit null object but how to realize it i don't know Any idea on how to solve it?