[英]Check if the first element of scanner in Java
我有一个 txt 文件,并且有单独的值,例如 1 2 3 10 15 2 5...,我将它们分配给 arraylist,如下所示。 在此期间,我需要省略第一个值,并且需要检测扫描的值是否是第一个值。 我尝试过诸如 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()
并避免解析它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.