我有一个文本文件,其中包含如下数据:
HW1 HW2 HW3 HW4 HW5
97 64 75 100 21 John
19 68 89 49 97 Kim
28 83 48 44 91 Kathy
69 66 78 87 85 Steve
99 94 93 96 91 Stacy
35 75 65 55 45 Faith
我尝试使用 BufferedReader 读取大小,以便可以将它们转换为多个数组(即 HW1arr
、HW2arr
等)。如何找到像这个 2D 文件一样的数组大小?
public static void main(String[] args) {
Scanner reader = null;
try {
File f = new File("inputHW7.txt");
reader = new Scanner(f);
} catch(FileNotFoundException e) {
}
double[][] size2d = null;
int count = 0;
int rowCount =0;
int colCount = 0;
int readChar = 0;
boolean empty = true;
rowCount = reader.nextInt();
for(int i=0 ; i<rowCount ; i++){
colCount = reader.nextInt();
size2d[i] = new double[colCount];
System.out.print("debugs column = "+size2d[i]);
for(int j=0 ; j<colCount ; j++){
size2d[i][j] = reader.nextDouble();
System.out.println("debug rows = "+ size2d[i][j]);
}
}
}
最佳答案
- 扫描仪提供 API 来检查输入流中是否存在其他项目(甚至是特定于类型的项目)
- hasNext* 系列 API 和 next* 系列 API 正是您所需要的。
- 将其与循环一起使用。
使用
ArrayList
,这样您就不需要事先知道大小。如果列数固定,您可以读取整行,并按空格分割。结果数组的长度将是您的列大小。然而行大小无法提前获得。因此应该首选 List 集合。
https://docs.oracle.com/javase/8/docs/api/index.html?java/util/Scanner.html
关于java将txt文件(2D)读取到多个2D数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50193676/