简体   繁体   中英

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. 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;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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