[英]How can I sort each column in a user input 3x3 2d array from smallest to largest? in JAVA language
我看过这个网站上的其他问题/答案。 然而似乎没有人专门解决这个问题。 到目前为止,这是我的代码,但我 > 得到一个
线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 3 at >> ColumnSorting.sortColumns(ColumnSorting.java:13) at >> TestColumnSorting.main(TestColumnSorting.java:19)
我运行它时出错。
public static int[][] sortColumns(int[][] matrix)
{
int tmp = 0;
int ct = 0;
for(int column = 0; column < matrix[ct].length; column++)
{
for(int row = 0; row < matrix.length; row++)
{
for (int i = row+1; i < matrix.length; i++)
{
if(matrix[row][column] > matrix[i][column])
{
tmp = matrix[row][column];
matrix[row][column] = matrix[i][column];
matrix[i][column] = tmp ;
}
}
}
ct++;
}
return matrix;
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
您收到此错误是因为在执行ct++
时 for 循环结束时,您最终会得到ct=3
。 由于数组索引从 0 开始,因此您的 3x3 列索引将从 0-2 开始。 因此,当ct=3
并且您执行matrix[ct].length
您将得到一个数组越界错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.