在线程“main”java.lang.ArrayIndexOutOfBoundsException中传递数组--异常:5

在线程“main”java.lang.ArrayIndexOutOfBoundsException中传递数组--异常:5,java,arrays,exception,Java,Arrays,Exception,问题是由于您的代码试图访问不存在的索引。请替换您的代码 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at com.company.Main.floyd2(Main.java:32) at com.company.Main.main(Main.java:23) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.r

问题是由于您的代码试图访问不存在的索引。请替换您的代码

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at com.company.Main.floyd2(Main.java:32)
at com.company.Main.main(Main.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Process finished with exit code 1

在for循环语句中增加i而不是j,从而导致

在第二个循环中,您使用的是i++而不是j++

堆栈跟踪显示:

     for(i=0; i < n; i++){ //This does not work
    for(j=0; j < n; i++){
        P[i][j] = 0;
    }
  }
这是一个循环:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
    at com.company.Main.floyd2(Main.java:32)
    at com.company.Main.main(Main.java:23)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
在这个循环中,增加i两次。所以它变成了n,也就是5。在内部循环中更改为j++

    for(i=0; i < n; i++){ //This does not work
        for(j=0; j < n; i++){
            P[i][j] = 0;
        }
    }
需要

for(i=0; i < n; i++){ //This does not work
    for(j=0; j < n; i++){
        P[i][j] = 0;
    }
}

确保增加在for循环j中测试的相同变量,在这种情况下

将stacktrace粘贴到问题。用于j=0;jException in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at com.company.Main.floyd2(Main.java:32) at com.company.Main.main(Main.java:23) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
    for(i=0; i < n; i++){ //This does not work
        for(j=0; j < n; i++){
            P[i][j] = 0;
        }
    }
for(i=0; i < n; i++){ //This does not work
    for(j=0; j < n; i++){
        P[i][j] = 0;
    }
}
 for(i=0; i < n; i++){ 
     for(j=0; j < n; j++){
         P[i][j] = 0;
     }
 }