简体   繁体   English

循环内的整数 ArrayList 拒绝打印

[英]ArrayList of Integers inside a while loop is refusing to print

I am solving a problem from Advent of Code, and trying to put the content of the input file into an arraylist, here's my code for that:我正在解决 Advent of Code 的问题,并尝试将输入文件的内容放入 arraylist,这是我的代码:

ArrayList<Integer> arrayList = new ArrayList<>();
    try (Scanner s = new Scanner(new File("input.txt")).useDelimiter(",")) {

        while (s.hasNext()) {
            int b = Integer.parseInt(s.next());
            arrayList.add(b);
        }

    }
    catch (FileNotFoundException e) {
        // Handle the potential exception
    }


    System.out.println(arrayList);

and when I run it, it does not print the arraylist.当我运行它时,它不会打印 arraylist。 I can't understand why, could someone tell me what I did wrong?我不明白为什么,谁能告诉我我做错了什么?

I used StringTokenizer and it works perfectly.我使用了 StringTokenizer,它运行良好。 I am not familiar with using Scanner to split items, so I converted it over into a StringTokenizer.我不熟悉使用 Scanner 拆分项目,所以我将其转换为 StringTokenizer。 Hope you're okay with that.希望你没事。

public static void main(String[] args) throws IOException {
        ArrayList<Integer> arrayList = new ArrayList<>();
        Scanner s = new Scanner(new File("input.in"));

        StringTokenizer st = new StringTokenizer(s.nextLine(), ",");

        while (st.hasMoreTokens()) {
            int b = Integer.parseInt(st.nextToken());
            arrayList.add(b);
        }
        s.close();

        System.out.println(arrayList);

}

This fills your ArrayList with the values you want这会用您想要的值填充您的 ArrayList

You can validate if you are able to read the file or not.您可以验证您是否能够读取该文件。 Your code can be modifed something like this.您的代码可以像这样修改。 Please check if it prints "File found".请检查它是否打印“找到文件”。 If not it means that file you are trying to read is not in classpath.如果不是,则意味着您尝试读取的文件不在类路径中。 You might want to refer https://mkyong.com/java/java-how-to-read-a-file/您可能想参考https://mkyong.com/java/java-how-to-read-a-file/

...
File source = new File("input.txt");
        if(source.exists()) {
            System.out.println("File found");
        }
        try (Scanner s = new Scanner(source).useDelimiter(",")) {
...

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

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