读取txt.file并使用java打印出其2d数字
我是java新手,我正在编写一个简单的程序来读取文件并只打印数字。因此,如果有一些文本,程序应该省略它们。但在我的程序中,如果有一些文本或空行,它将存储在数组0中;这是我的密码读取txt.file并使用java打印出其2d数字,java,Java,我是java新手,我正在编写一个简单的程序来读取文件并只打印数字。因此,如果有一些文本,程序应该省略它们。但在我的程序中,如果有一些文本或空行,它将存储在数组0中;这是我的密码 import java.io.*; import java.util.*; public class FileR { public static void main(String[] args) throws Exception { int[][] desktop; int ro
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][];
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) {
String[] nums = line.split("\\s*,\\s*");
desktop[row] = new int[nums.length];
for (int col = 0; col < nums.length; col++) {
nums[col] = nums[col].replaceAll("[^0-9]", "");
if (!(nums[col].isEmpty())) {
int n = Integer.parseInt(nums[col].trim());
desktop[row][col] = n;
}
}
row++;
}
print(desktop);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
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();
}
}
}
输出应该只打印包含数字的2d数组,而忽略文本,但不是打印0,如下所示:
0
0
0
0
0
2 2 2 2
0
2 0 0 0 0 0 0 0 0 2
2 0 1 0 3 0 4 0 0 2
2 0 0 0 3 0 4 0 0 2
2 0 0 0 3 0 4 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 0 0 0 0 0 0 2
2 0 0 0 0 0 2
2 2 2 2 2 2 2 2 2 2
0
0
0
不幸的是,我不知道如何修复它们,请帮助
P.如果您有任何问题,请告诉我您有一个int(基本类型)数组。因此,数组值在开始时为零
您可以将桌面设置为一个整数[]],并且在打印时跳过空值。问题是我的类型应该是int(原语),我的意思是,存储到int[][]数组,也许还有其他选项可以解决这个问题
0
0
0
0
0
2 2 2 2
0
2 0 0 0 0 0 0 0 0 2
2 0 1 0 3 0 4 0 0 2
2 0 0 0 3 0 4 0 0 2
2 0 0 0 3 0 4 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 0 0 0 0 0 0 2
2 0 0 0 0 0 2
2 2 2 2 2 2 2 2 2 2
0
0
0