英文:
ArrayList of Integers inside a while loop is refusing to print
问题
以下是翻译好的内容:
我正在解决《编程之圣诞日》(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) {
// 处理可能的异常
}
System.out.println(arrayList);
但当我运行它时,它并没有打印出ArrayList。我不明白为什么,有人能告诉我我做错了什么吗?
英文:
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?
答案1
得分: 0
我使用了StringTokenizer,它运行得很完美。我对使用Scanner分割项目不太熟悉,所以我将其转换为了StringTokenizer。希望您对此没有意见。
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);
}
这将使用所需的值填充您的ArrayList。
英文:
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
答案2
得分: 0
你可以验证是否能够读取文件。你的代码可以像这样进行修改。请检查是否打印出 "File found"。如果没有打印出来,这意味着你试图读取的文件不在类路径中。你可能希望参考 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(",")) {
...
英文:
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(",")) {
...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论