【发布时间】:2014-03-03 05:05:40
【问题描述】:
试图从文件中读取 int。我的问题是我的代码读取了第一行中的所有整数,但在下一行它跳过了第一个数字。 为了说明我的文件有这些数字: 1, 4, 6, 7, 8, 11, 9, 1、4、6、7、8、11、12、 2, 4, 6, 7, 11, 12, 0,
但是当我使用下面的代码时,它只打印 1 4 6 7 8 11 9 然后 4 6 7 8 11 12 然后 2... 它会跳过第一个。
Scanner file = null;
ArrayList<Integer> listtwo = new ArrayList<>();
try {
file = new Scanner(new File(filename+".txt")).useDelimiter(",| ");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while(file.hasNext()){
if (file.hasNextInt()){
listtwo.add(file.nextInt());
}
file.next();
}
for (Integer i: listtwo) System.out.println(i);
【问题讨论】:
-
@ambigram_maker 错误。
hasNext...()方法不会跳过任何内容。
标签: java file int java.util.scanner