簡體   English   中英

檢查Java中scanner的第一個元素

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM