我有一个 txt 文件,其中有单独的值,例如 1 2 3 10 15 2 5...,我将它们分配给数组列表,如下所示。在此期间,我需要省略第一个值,并且需要检测扫描的值是否是第一个值。我尝试过类似indexOf 等但无法修复。如何检测第一个元素并使用 if()?
private static ArrayList<Integer> convert() throws FileNotFoundException {
Scanner s = new Scanner(new File("C:\\list.txt"));
ArrayList<Integer> list = new ArrayList<Integer>();
while (s.hasNext()) {
int next = Integer.parseInt(s.next());
if (// s.next() is the first element of list.txt) {
}
list.add(next);
}
s.close();
return list;
}
最佳答案
只需使用计数器来确定它是否是第一个元素。
private static ArrayList<Integer> convert() throws FileNotFoundException {
Scanner s = new Scanner(new File("C:\\list.txt"));
ArrayList<Integer> list = new ArrayList<Integer>();
int i = 0;
while (s.hasNext()) {
int next = Integer.parseInt(s.next());
if (i == 0) {
//must be first element
} else {
// other elements
}
i++;
list.add(next);
}
s.close();
return list;
}
您还可以使用 Scanner.nextInt()
和 Scanner.hasNextInt()
并避免解析它。
关于java - 检查Java中scanner的第一个元素是否,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61143647/