gpt4 book ai didi

java - 线程中的异常 "main"java.lang.ArrayIndexOutOfBoundsException : 5

转载 作者:行者123 更新时间:2023-12-01 23:23:48 24 4
gpt4 key购买 nike

我需要帮助来完成我当前正在做的一些数组分配。到目前为止,我设法纠正了部分代码,但这个问题仍然存在..

public class AssignmentArray1 {
public static void main(String[] args) {

int a[][] = new int[ 10 ][ 5 ];

for ( int i = 0; i < a.length; i++ )
{
for ( int j = 0; j < a[ i ].length; j++ ) {
a[ j ][ i ] = j;
}
}
for ( int i = 0; i < a.length; i++ )
{
for ( int j = 0; j < a[ i ].length; j++ )
System.out.printf( "%d ", a[ j ][ i ] );
System.out.println();
}
}

}

这有什么问题吗?我不明白为什么会收到错误消息

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at assignmentarray1.AssignmentArray1.main(AssignmentArray1.java:25)

很明显 a[ j ][ i ] = j; 有问题?但到底是什么?

最佳答案

看来您不小心将索引交换为 a 数组。

这个:

            a[ j ][ i ] = j;

应该是:

            a[ i ][ j ] = j;

还有这个:

            System.out.printf( "%d ", a[ j ][ i ] );

应该是:

            System.out.printf( "%d ", a[ i ][ j ] );

关于java - 线程中的异常 "main"java.lang.ArrayIndexOutOfBoundsException : 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20315039/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com