有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    了解更多的上下文会很有帮助,尤其是: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);