我正在尝试在android上编写游戏,进行文本搜索。
我有一个叫做“工作”的过程,它的作用是使玩家有机会选择工作地点以及他想工作多少时间,然后处理这些信息。
下面是两个方法“ checkWorkPlaces()”的代码,该方法检查城市播放器中是否有工作场所,然后调用“ chooseWorkPlace()” >”方法,让玩家有机会选择自己想去的工作地点。
hideButtons()-在屏幕上隐藏一些按钮[对我的问题并不重要]
protected void checkWorkPlaces() {
answerContainer.clear();
if (player.location.workPlaces.length > 0) {
tvInfo.setText("In " + player.location.name + " there are a few places to work:");
for (WorkPlace workPlace : player.location.workPlaces) {
tvInfo.append("\n" + workPlace.defenition);
}
tvInfo.append("Where do you want to work?");
chooseWorkPlace();
} else {
tvInfo.setText("There is nowhere to work in " + player.location.name);
}
}
protected void chooseWorkPlace() {
hideButtons();
btnMainGame.setText(getString(R.string.save));
btnMainGame.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (etInput.getText().toString().isEmpty()){
Toast.makeText(MainActivity.this, "Please enter something", Toast.LENGTH_SHORT).show();
chooseWorkPlace();
} else {
answerContainer.add(etInput.getText().toString().toLowerCase());
}
}
});
String choice = answerContainer.get(0).toString().toLowerCase();
answerContainer.clear();
if (!Objects.equals(choice, "back")) {
for (WorkPlace workPlace : player.location.workPlaces) {
if (Objects.equals(workPlace.name.toLowerCase(), choice)) {
answerContainer.add(workPlace);
return;
}
}
tvInfo.append("\n\nThere is no such work place as: " + choice + ", try again");
chooseWorkPlace();
}
}
因此,问题在于,当程序开始调用 chooseWorkPlace()方法时,它会使用java.lang.IndexOutOfBoundsException
停止程序E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.griseostrigiformes.textwarrior, PID: 4916
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at com.example.griseostrigiformes.textwarrior.MainSystem.MainActivity.chooseWorkPlace(MainActivity.java:521)
at com.example.griseostrigiformes.textwarrior.MainSystem.MainActivity.checkWorkPlaces(MainActivity.java:492)
at com.example.griseostrigiformes.textwarrior.MainSystem.MainActivity$2.onClick(MainActivity.java:124)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
如何解决此问题?
答案 0 :(得分:0)
这行似乎给你错误,
String choice = answerContainer.get(0).toString().toLowerCase();
在获取零索引元素之前,您可能应该首先检查answerContainer
的大小吗?或者,您应该调试为什么answerContainer
为空。