繁体   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