简体   繁体   中英

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:

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. I can't understand why, could someone tell me what I did wrong?

I used StringTokenizer and it works perfectly. I am not familiar with using Scanner to split items, so I converted it over into a 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

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/

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

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