英文:
Check if the first element of scanner in Java
问题
private static ArrayList<Integer> convert() throws FileNotFoundException {
Scanner s = new Scanner(new File("C:\\list.txt"));
ArrayList<Integer> list = new ArrayList<Integer>();
boolean isFirstValue = true; // Flag to detect the first element
while (s.hasNext()) {
int next = Integer.parseInt(s.next());
if (isFirstValue) {
isFirstValue = false; // Set the flag to false after encountering the first element
} else {
list.add(next);
}
}
s.close();
return list;
}
英文:
I have a txt file and there are separate values like 1 2 3 10 15 2 5... and I assign them to an arraylist as shown below. During this I need to omit the first value and I need to detect if the scanned value is the first value. I have tried something like indexOf, etc but not manage to fix. How can I detect the first element and use 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;
}
答案1
得分: 1
只需使用计数器来判断是否为第一个元素。
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) {
// 必须是第一个元素
} else {
// 其他元素
}
i++;
list.add(next);
}
s.close();
return list;
}
你也可以使用 Scanner.nextInt()
和 Scanner.hasNextInt()
,避免了必须进行解析。
英文:
Just use a counter to determine if it is the first element.
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;
}
You can also use Scanner.nextInt()
and Scanner.hasNextInt()
and avoid having to parse it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论