【发布时间】:2019-03-09 10:30:08
【问题描述】:
我制作了一个应用程序,它从两个文本文件(一个带有单词,另一个带有定义)中获取单词和定义。使用随机数生成要显示的单词,然后随机排列 5 个定义以及正确的定义以显示选项。该应用程序运行完美,但是当使用列表视图单击任何选项时,该应用程序将停止工作。
ArrayList<String> word=new ArrayList<>();
List<String> dfn=new ArrayList<>();
String que="",ans="";
int counter=0;
private void random(){
Random num = new Random();
int nw = num.nextInt(word.size());
que = word.get(nw);
ans = dfn.get(nw);
dfn.remove(ans);
Collections.shuffle(dfn);
dfn = dfn.subList(0,4);
dfn.add(ans);
Collections.shuffle(dfn);
}
TextView t;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
Scanner sc = new Scanner(getResources().openRawResource(R.raw.word2));
Scanner sc2 = new Scanner(getResources().openRawResource(R.raw.def2));
while(sc.hasNextLine()&&sc2.hasNextLine()){
String a = sc.nextLine();
String b = sc2.nextLine();
word.add(a);
dfn.add(b);
我猜上面的部分很好。
}
sc.close();
sc2.close();
random();
t = (TextView) findViewById(R.id.t);
t.setText(que);
run();
}
ArrayAdapter<String> adap;
public void run(){
ListView list = (ListView) findViewById(R.id.li);
adap = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
dfn
);
list.setAdapter(adap);
list.setOnItemClickListener((adapterView, view,i,l)->{//lambda expression
if(dfn.get(i).equals(ans)){
Toast.makeText(getApplicationContext(),"Correct!",Toast.LENGTH_SHORT).show();
counter++;
}
else{
Toast.makeText(getApplicationContext(),"Wrong!",Toast.LENGTH_SHORT).show();
}
TextView t2 = (TextView) findViewById(R.id.t2);
t2.setText("Score : "+counter);
random();
t.setText(que);
run();
}
);
}
}
堆栈跟踪: 致命例外:主要 进程:com.example.ankitrath.wordguess,PID:2769 java.lang.IndexOutOfBoundsException:索引:264,大小:5 在 java.util.ArrayList$SubList.get(ArrayList.java:1049) 在 com.example.ankitrath.wordguess.GameActivity.random(GameActivity.java:27)
ans = dfn.get(nw);
【问题讨论】:
-
发布堆栈跟踪
-
什么是 t2 ?它在列表视图里面吗?
-
刚刚修复了日志猫并在帖子中添加了堆栈跟踪
-
t2 用于显示分数
标签: java android listview arraylist