我的代码在我的代码中超出了数组的范围,但在前两个输入出现问题后它将运行并崩溃

问题描述 投票:0回答:1
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);

这是困扰我整个项目的代码,我正在使用它来限制某些动作,但是它使我的整个游戏崩溃了,任何人都可以告诉我哪里出了问题。该程序将运行,但在第二次用户输入后显示异常的情况下崩溃

java arrays do-while restriction
1个回答
0
投票
特别是可以看到更多的上下文,这是有帮助的: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);

这样,您可以将问题简化为更具体的内容(例如,为什么choice2index1是某个值)。 

通常,在访问数组之前检查索引是否超出界限通常也是一个好主意,尤其是在处理用户输入时(看起来好像是在处理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);

© www.soinside.com 2019 - 2024. All rights reserved.