![](/img/trans.png)
[英]Cannot add to arraylist inside while loop inside the main method
[英]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) {
// Handle the potential exception
}
System.out.println(arrayList);
當我運行它時,它不會打印 arraylist。 我不明白為什么,誰能告訴我我做錯了什么?
我使用了 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
您可以驗證您是否能夠讀取該文件。 您的代碼可以像這樣修改。 請檢查它是否打印“找到文件”。 如果不是,則意味着您嘗試讀取的文件不在類路徑中。 您可能想參考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.