如何从最小到最大对用户输入的 3x3 二维数组中的每一列进行排序?使用 JAVA 种语言
How can I sort each column in a user input 3x3 2d array from smallest to largest? in JAVA language
Ive looked at other questions/answers on this website. however none
seem to be solving this problem specifically. This is my code so far but I am > getting a
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at > > ColumnSorting.sortColumns(ColumnSorting.java:13) at > > TestColumnSorting.main(TestColumnSorting.java:19)
error when i run it.
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
时,你将得到一个数组越界错误。
Ive looked at other questions/answers on this website. however none seem to be solving this problem specifically. This is my code so far but I am > getting a
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at > > ColumnSorting.sortColumns(ColumnSorting.java:13) at > > TestColumnSorting.main(TestColumnSorting.java:19)
error when i run it.
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
时,你将得到一个数组越界错误。