do {
if (counter%2==0 && HP1[choice2] <= 0) {
System.out.println("You cannot switch to that pokemon it has already fainted, choose someone else");
choice2 = reader.nextInt();
}
else if (counter%2==0 && choice2 == index1) {
System.out.println(myParty[index1] + " is already in battle. Please select a different pokemon.");
choice2 = reader.nextInt();
}
} while (counter%2==0 && HP1[choice2] <= 0 || counter%2==0 && choice2 == index1);
这是困扰我整个项目的代码,我正在使用它来限制某些动作,但是它使我的整个游戏崩溃了,任何人都可以告诉我哪里出了问题。该程序将运行,但在第二次用户输入后显示异常的情况下崩溃
index1
的值从哪里来?如何更改?有关调试数组超出范围的提示,例外:在访问数组之前,打印数组大小和将要访问的索引。例如,在您的代码中,在第一个if
语句之前,添加:
System.out.println("HP1 array size: " + HP1.length);
System.out.println("About to access index: " + choice2);
System.out.println("myParty array size: " + myParty.length);
System.out.println("About to access index: " + index1);
这样,您可以将问题简化为更具体的内容(例如,为什么choice2
或index1
是某个值)。通常,在访问数组之前检查索引是否超出界限通常也是一个好主意,尤其是在处理用户输入时(看起来好像是在处理
reader
对象。]您可以这样检查
do { if (choice2 < 0 || choice2 > (HP1.length - 1) || index1 < 0 || index1 > (myParty.length - 1)) { // handle the error } else if (counter%2==0 && HP1[choice2] <= 0) { System.out.println("You cannot switch to that pokemon it has already fainted, choose someone else"); choice2 = reader.nextInt(); } else if (counter%2==0 && choice2 == index1) { System.out.println(myParty[index1] + " is already in battle. Please select a different pokemon."); choice2 = reader.nextInt(); } } while (counter%2==0 && HP1[choice2] <= 0 || counter%2==0 && choice2 == index1);