【发布时间】:2012-02-25 18:37:09
【问题描述】:
这是我的第一个问题,但我会尽力问好。无论如何,我正在尝试从 Android 中的文本文件中读取数据,但由于某种原因,它一直没有返回任何内容 - 即 IndexOutOfBounds 异常。所有相关代码:
public Question getNextQuestion(int num) {
Log.d(TAG, array.toString());
return array.get(num+1);
}
public ArrayList<Question> getData(String str) throws NumberFormatException, IOException {
Log.d(TAG, "STARTING getData");
Log.d(TAG, str);
ArrayList<Question> a = new ArrayList<Question>();
String[] strline = str.split("//");
for (int j = 0; j < strline.length; j++) {
if (strline[j] == null) {
strline[j] = "TESTING";
Log.d(TAG, strline[j]);
}
}
int num = 0;
int x = 0;
String y = strline[x];
while (x == 0 || y != null) {
num++;
String[] data = y.split("//");
Log.d(TAG, y);
if (data.length >= 7) {
a.add(new Question(Integer.parseInt(data[0]), data[1], data[2], data[3], data[4], data[5], Integer.parseInt(data[6])));
Log.d(TAG, a.get(a.size()).getText());
}
else if (data.length >= 3) {
a.add(new Question(Integer.parseInt(data[0]), data[1], data[2]));
Log.d(TAG, a.get(a.size()).getText());
}
x++;
if (x < strline.length)
y = strline[x];
else
break;
}
for (int i=0; i<a.size(); i++){
Log.d(TAG, a.get(i).getText());
}
Log.d(TAG, "ENDING getdata");
return a;
}
public ArrayList<Question> openFile() throws IOException {
Log.d(TAG, "STARTING openFile()");
//FileReader fr = new FileReader("data/data/scibowl.prog/questionsb.txt");
FileInputStream fis;
String storedString = "";
try {
fis = openFileInput("questionsb.txt");
DataInputStream dataIO = new DataInputStream(fis);
String strLine = null;
while ((strLine = dataIO.readLine()) != null) {
storedString = storedString + strLine;
}
dataIO.close();
fis.close();
}
catch (Exception e) {
}
array = getData(storedString);
Log.d(TAG, "DID open file, ending openFile()");
return array;
}
这将在 LogCat 中打印:
onCreate done
STARTING openFile()
STARTING getData
ENDING getdata
DID open file, ending openFile()
right before Toast.makeText
[]
Caused by: java.lang.IndexOutOfBoundsException: Invalid location 1, size is 0
at java.util.ArrayList.get(ArrayList.java:341)
at scibowl.prog.Round.getNextQuestion(Round.java:55)
at scibowl.prog.RoundView.<init>(RoundView.java:26)
at scibowl.prog.Round.onCreate(Round.java:35)
我几乎尝试了从 StringBuffers 到 FileInputStreams 再到 BufferedReaders 的所有内容,并阅读了相关的 Android 文档,但请随时告诉我,我阅读的内容还不够努力。有谁知道为什么我总是得到没有元素的数组?
供参考的文本文件,尽管稍作编辑以符合块引用规则:
1//在标准电磁波谱上,伽马射线和紫外线之间的频率是多少?//无线电波//微波//X射线//红外线//1
2//电磁波谱上的哪些波大致包含10^9赫兹到10^12赫兹的频率?//可见光//伽马射线//紫外线//微波//3
3//大约有多少百分比的美国电力来自煤炭?//30%//40%//50%//60%//0
4//如果一个100公斤的人从静止开始走路,在2秒内以恒定加速度加速到4.0m/s,他做了多少功?//600 J//800 J//1200 J/ /2000 焦//1
【问题讨论】: