簡體   English   中英

在Java中將文本文件中的值添加到arraylist

[英]Adding values from text file to arraylist in Java

我正在Android Studio中的多選Java應用程序上工作,並且嘗試獲取下面的代碼以在每個逗號處拆分文本文件,實質上是使逗號索引前的字符串為[0],而使逗號后的字符串索引[1]。 我需要在代碼中進行哪些更改才能使其正常工作? 當我嘗試使用存儲在[1]的任何值時,我的應用程序不斷因出站錯誤而崩潰

    public class ActivityTwo extends AppCompatActivity {
int sizeOfArray;
String[][] qAndA;//Stores Questions and Answers

String[] split = new String[5];
ArrayList<String>arrayListTerms = new ArrayList<String>();
ArrayList<String>arrayListDef = new ArrayList<String>();
HashMap<String, String> qMatch = new HashMap<>();//Matches correct answer with current question
List<String> lines = new ArrayList<String>();

public static final String TAG =" ";

//for(int i = 0; i < 9; i++){
//qAndA[0][i] = arrayListDef.get(i);
//}
//Switch & do same for questions
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_2);

    InputStream is = this.getResources().openRawResource(R.raw.textfile);
    BufferedReader myBufferedReader = new BufferedReader(new InputStreamReader(is));
    String line;

    try {

        while((line = myBufferedReader.readLine()) != null) {
            String[] split = line.split(Pattern.quote(","));
            String question1 = split[0];
            String question2 = split[1];
            lines.add(question1);
            lines.add(question2);
        }
        Log.i(TAG, "Textfile Loaded.");
        myBufferedReader.close();
    } catch (FileNotFoundException ex) {
        Log.e(TAG, "Unable to open text file.");
    } catch (IOException ex){
        Log.e(TAG, "Error reading text file.");
    }

    Collections.shuffle(arrayListDef);
    sizeOfArray = arrayListDef.size();

發生這種情況的原因是,您正在從文件中讀取的行之一不包含任何“,”,這就是為什么要使索引超出綁定異常。 您正在使用的閱讀器正在逐行讀取基數,這就是為什么它在讀取沒有昏迷的行時會崩潰的原因。

造成此問題的另一個原因是文件末尾有一個空行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM