简体   繁体   English

检查Java中scanner的第一个元素

[英]Check if the first element of scanner in Java

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.我有一个 txt 文件,并且有单独的值,例如 1 2 3 10 15 2 5...,我将它们分配给 arraylist,如下所示。 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.我尝试过诸如 indexOf 之类的东西,但无法修复。 How can I detect the first element and use if()?如何检测第一个元素并使用 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;
}

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.您还可以使用Scanner.nextInt()Scanner.hasNextInt()并避免解析它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM