【发布时间】:2021-01-03 20:44:39
【问题描述】:
我正在尝试从 java 中的用户输入打开一个文件,然后读取该文件并仅获取每行中的整数,然后将其放入一个数组并返回该数组。我更熟悉python在文件中抓取项目而不是java。
一行文件的示例内容:
34 a 55 18 47 89 b 45 67 59 abbbb 88 37 20 27 10 78 39 21 nm ghff
我的代码:
private static int[] getArray(){
List<Integer> temp = new ArrayList<Integer>();
System.out.print("Please input the name of the file to be opened: ");
try{
String filename = in.next();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
while (inputFile.hasNextInt()){
temp.add(inputFile.nextInt());
}
} catch (FileNotFoundException e){
System.out.println("---File Not Found! Exit program!---");
System.exit(0);
}
int[] array = new int[temp.size()];
for (int i = 0; i < array.length; i++){
array[i] = temp.get(i);
}
return array;
}
编辑:
我发现我的 while 循环是错误的。应该是这样的:
while (inputFile.hasNext()){
if (inputFile.hasNextInt()){
temp.add(inputFile.nextInt());
}
else{
inputFile.next();
}
}
【问题讨论】:
-
回答了一部分,但我仍然得到 0 的回报,因为它似乎没有读取整数的文件
标签: java arrays file methods return