在我的最新項(xiàng)目中,我使用了一個名為“ atestfile.txt ”的 .txt 文件,該文件位于我創(chuàng)建的項(xiàng)目 /raw 文件夾中:這是它的內(nèi)容:現(xiàn)在使用這幾行簡單的代碼..我希望我的應(yīng)用程序?qū)⑽谋疚募械膯卧~逐行插入到我的 ArrayList 中,如這個問題的第一個答案所示。但是,沒有面包會出現(xiàn),甚至更糟的是,我會收到一個IndexOutOfBoundsException異常的test.get(3); 我使用的線路和應(yīng)用程序崩潰。我一整天都試圖擺脫這個錯誤,但還沒有成功。所以因?yàn)檫@里有很多聰明的人,我很想了解這個問題,我想我會在把我的電腦扔出窗外之前先向你們尋求幫助。我將向你們提供我的錯誤消息、復(fù)制和可粘貼代碼以及我的數(shù)據(jù)包結(jié)構(gòu),以獲得有關(guān)此問題的更多幫助。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貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超3個贊
您在每個循環(huán)中兩次調(diào)用 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
提交
取消
