java My code在我的代码中出现数组越界异常,但在前两次输入出错后,它将运行并崩溃
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);
这段代码打乱了我的整个项目,我用它来限制某些行为,但它破坏了我的整个游戏,有人能告诉我哪里出了问题吗。程序将运行,但在显示异常的第二次用户输入后崩溃
# 1 楼答案
了解更多的上下文会很有帮助,尤其是:
index1
的值来自哪里?它是如何改变的调试数组越界异常的提示:在访问数组之前,打印数组大小和即将访问的索引。例如,在代码中,在第一个
if
语句之前添加:通过这种方式,您可以将问题简化为更具体的问题(例如,为什么
choice2
或index1
是某个特定值)通常,在访问数组之前检查索引是否超出范围也是一个好主意,尤其是在处理用户输入时(就像处理
reader
对象时那样)你可以这样检查一下