如何将用户输入3x3 2d阵列中的每列从最小到最大排序?用JAVA语言

时间:2022-05-05 13:43:12

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.

我看过这个网站上的其他问题/答案。但是似乎没有人具体解决这个问题。这是我的代码到目前为止,但我>在线程“main”中获取异常java.lang.ArrayIndexOutOfBoundsException:3 >>> ColumnSorting.sortColumns(ColumnSorting.java:13)>>> 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;

1 个解决方案

#1


1  

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3

线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:3

You're getting this error because at the end of your for loops when you do ct++ you will eventually get ct=3. Since array indexing starts at 0, your 3x3 column indices will go from 0-2. So when ct=3 and you do matrix[ct].length you will get an array out of bounds error.

你得到这个错误,因为当你执行ct ++时你的for循环结束时你最终会得到ct = 3。由于数组索引从0开始,因此3x3列索引将从0到2。因此,当ct = 3并且你做矩阵[ct] .length时,你会得到一个超出界限的数组错误。

#1


1  

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3

线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:3

You're getting this error because at the end of your for loops when you do ct++ you will eventually get ct=3. Since array indexing starts at 0, your 3x3 column indices will go from 0-2. So when ct=3 and you do matrix[ct].length you will get an array out of bounds error.

你得到这个错误,因为当你执行ct ++时你的for循环结束时你最终会得到ct = 3。由于数组索引从0开始,因此3x3列索引将从0到2。因此,当ct = 3并且你做矩阵[ct] .length时,你会得到一个超出界限的数组错误。