将文本文件中的值添加到Java中的ArrayList中

问题描述:

我正在开发Android Studio中的多选java应用程序,并且我试图获取下面的代码以便在每个逗号处分割我的文本文件,逗号索引[0]和逗号索引[1]后面的字符串。在我的代码中需要更改什么才能使其工作?我的应用程序总是崩溃上outofbounds错误,当我尝试使用存储在[1]将文本文件中的值添加到Java中的ArrayList中

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(); 
+0

什么是您的输入示例?这听起来好像你的字符串没有被分割。所以split [0]包含整条线,split [1]将是空的(不存在和不包含边界) – Samuel

+0

@Samuel它来自这样的文本文件:哪种语言最常用于Android应用程序开发?这些程序通常用于Android应用程序开发? –

+0

我与yannick1976。当你使用更简单的形式时会发生什么String [] split = string.split(“,”);.您的模式可能会尝试识别与其他任何内容不同的内容,因此永远不会匹配,因此也不会分割字符串。 – Samuel

出现这种情况的原因,任何价值在于,你是从文件中读取不包含任何行之一','这就是为什么你要获得索引超出界限的例外。 您正在使用的读者正在逐行读取基准线,这就是为什么当它读取一条没有昏迷的线时它会崩溃。

这样做的另一个原因是你的文件在它的末尾有一个空行。

+0

Java,Android应用程序开发最常用的语言是什么?这是我的第一行。有一个逗号。 –

+0

如果行不......我编辑了答案。 @JeremyStone –

+0

另一个想法是确保你的文件末尾没有空行@JeremyStone –