检查Java中Scanner的第一个元素

huangapple go评论72阅读模式
英文:

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&lt;Integer&gt; convert() throws FileNotFoundException {
    Scanner s = new Scanner(new File(&quot;C:\\list.txt&quot;));
    ArrayList&lt;Integer&gt; list = new ArrayList&lt;Integer&gt;();

    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&lt;Integer&gt; convert() throws FileNotFoundException {
    Scanner s = new Scanner(new File(&quot;C:\\list.txt&quot;));
    ArrayList&lt;Integer&gt; list = new ArrayList&lt;Integer&gt;();
    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.

huangapple
  • 本文由 发表于 2020年4月10日 23:37:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/61143647.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定