【发布时间】:2018-11-15 04:08:48
【问题描述】:
我有一个包含 15 个全名的数组,我如何将它分成 2 个数组(名字和姓氏)下面是我的全名数组的方法
public static void readData(String file) throws FileNotFoundException {
x = new Scanner(new File(file));
//count number of names in the array
int n = 0;
while(x.hasNextLine()) {
n++;
x.nextLine();
}
//open another scanner to avoid null
Scanner x1 = new Scanner(new File(file));
name = new String[n];
//get the array and print
for(int i = 0; i < name.length; i++ )
name[i] = x1.nextLine();
System.out.println(Arrays.toString(name));
}
【问题讨论】:
-
创建两个数组。当您从文件中读取
String时,在分隔符上拆分,我假设这是一个“空格”,然后将每个元素添加到相应的数组中 -
只是出于好奇,您为什么要打开“另一个扫描仪以避免空值”?似乎完全没有必要。
-
你为什么要把它读入一个数组?只需一次拆分并打印。此外,您泄漏的不是一个而是两个文件句柄!
-
@Carcigenicate 查看代码,他们试图提前确定文件中的行数......他们需要将
Scanner重置为文件的开头,这就是为什么我假设他们使用了两个扫描仪,但也没有关闭……而且通常会弄得一团糟(我怀疑这会是 NPE)