【问题标题】:Bubble Sort 2D Array Alphabetically Java冒泡排序 2D 数组按字母顺序 Java
【发布时间】:2021-04-15 17:52:26
【问题描述】:

我能否得到第二双眼睛告诉我为什么我的数组在每次打印时都没有被排序?我正在尝试对 2 x 3 数组( Student [][] 教室 = new Student[2][3]; )进行排序并按姓氏字母顺序排列。我的注释代码如下:

//DECLARES THE CLASSROOM ARRAY 
  public static void sort(Student [][] array) {
      //In order for the loop to work, we must initialize values so that we can "Run" through the variables in our loop. 
      
      int a,b; //These are the variables used during loops. Type integer of positional spot needed. 
     
     
      //We will create a temporary Student called "temporary" 
      //This will host values when and if the "swap" occurs. 
      Student temporary = new Student();
      //The four loop initializing values; such as a, b will loop throughout each value of the area. 
      
      //The first two elements check the elements of the array. 
      //The last two loops run through the entirety of the array to run a compare check. 
      for (a = 0 ; a < 2 ; a++){
          
          for(b = 0 ; b < 3; b++) {
            if (b == 2 && a != 1) {
 
                if((array[a][b].getLastName().compareToIgnoreCase(array[a+1][0].getLastName()) > 0))
                temporary = array[a][b];
                array[a][b] = array[a+1][0];
                array[a+1][0] = temporary;
            }
            else if (b < 2) 
            {if((array[a][b].getLastName().compareToIgnoreCase(array[a][b+1].getLastName()) > 0)) 
                temporary = array[a][b];
                array[a][b] = array[a][b+1];
                array[a][b+1] = temporary;
            }
                
          }
          }//End-For B Loop
      }//End-For A Loop
  //End-Method Check
  

【问题讨论】:

  • 发布此类问题时,请附上课程的最低版本(在本例中为学生)和一些测试数据。基本上是minimal reproducible example。您可能想解释管理该内部循环的标准。

标签: java bubble-sort


【解决方案1】:

看看你的代码格式!始终使用 {}。 如果您不使用弯括号,则只有下一行取决于 if。所以你的代码说:

  if((array[a][b].getLastName().compareToIgnoreCase(array[a+1][0].getLastName()) > 0)){
      temporary = array[a][b];
  }
  array[a][b] = array[a+1][0];
  array[a+1][0] = temporary;

你可能想要什么:

  if((array[a][b].getLastName().compareToIgnoreCase(array[a+1][0].getLastName()) > 0)){
      temporary = array[a][b];
      array[a][b] = array[a+1][0];
      array[a+1][0] = temporary;
  }

如果你使用 Eclipse,你可以使用 CTRL + SHIFT + F 来自动格式化。

【讨论】:

  • 提及 Eclipse 与问题无关。您不知道 OP 使用的是什么 IDE。您也不会知道设置或什至想要的格式首选项。
  • @WJS 你是对的。但是上面的代码绝对没有系统。这很可能导致了问题。初学者应该习惯任何格式化系统,在 Eclipse 中您可以使用这种方法。但是我当然无法判断提问者是否在使用这个 IDE。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-14
  • 2012-04-06
  • 2015-08-08
  • 2011-07-16
  • 2017-06-18
  • 1970-01-01
相关资源
最近更新 更多