在我的最新項目中,我使用了一個名為“ atestfile.txt ”的 .txt 文件,該文件位于我創建的項目 /raw 文件夾中:這是它的內容:現在使用這幾行簡單的代碼..我希望我的應用程序將文本文件中的單詞逐行插入到我的 ArrayList 中,如這個問題的第一個答案所示。但是,沒有面包會出現,甚至更糟的是,我會收到一個IndexOutOfBoundsException異常的test.get(3); 我使用的線路和應用程序崩潰。我一整天都試圖擺脫這個錯誤,但還沒有成功。所以因為這里有很多聰明的人,我很想了解這個問題,我想我會在把我的電腦扔出窗外之前先向你們尋求幫助。我將向你們提供我的錯誤消息、復制和可粘貼代碼以及我的數據包結構,以獲得有關此問題的更多幫助。package com.niklas.cp.citypopulation; final ArrayList<String> test = new ArrayList<String>(); try { Scanner scanner = new Scanner(new File("android.resource:// com.niklas.cp.citypopulation/raw/atestfile.txt")); while(scanner.hasNextLine()){ makeToast(scanner.nextLine(),1); test.add(scanner.nextLine()); } scanner.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } String abc = test.get(3); tv_highscore.setText(abc);
1 回答

倚天杖
TA貢獻1828條經驗 獲得超3個贊
您在每個循環中兩次調用 scanr.nextLine() ,但只將第二行添加到test,因此test只有三行。
你必須這樣寫
while(scanner.hasNextLine()) {
String s = scanner.nextLine();
makeToast(s,1);
test.add(s);
}
如果它拋出 FileNotFoundException 嘗試以下
InputStream file = getResources().openRawResource(R.raw.atestfile);
Scanner scanner = new Scanner(file);
添加回答
舉報
0/150
提交
取消