气泡按字母顺序排序2D数组Java
我能不能让另一双眼睛告诉我为什么我的数组没有在每次打印时进行排序?我正在尝试对一个2 x 3数组(学生[][]教室=新学生[2][3];)进行排序,并按姓氏按字母顺序排列。我的注释代码如下:气泡按字母顺序排序2D数组Java,java,bubble-sort,Java,Bubble Sort,我能不能让另一双眼睛告诉我为什么我的数组没有在每次打印时进行排序?我正在尝试对一个2 x 3数组(学生[][]教室=新学生[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 w
//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
//声明教室数组
公共静态无效排序(学生[][]数组){
//为了使循环工作,我们必须初始化值,以便能够“运行”循环中的变量。
int a,b;//这些是循环期间使用的变量。需要输入位置点的整数。
//我们将创建一个名为“临时”的临时学生
//当发生“交换”时,这将承载值。
临时学生=新学生();
//四个循环初始化值;例如a、b将在区域的每个值中循环。
//前两个元素检查数组的元素。
//最后两个循环遍历整个数组以运行比较检查。
对于(a=0;a<2;a++){
对于(b=0;b<3;b++){
如果(b==2&&a!=1){
if((数组[a][b].getLastName().CompareTIgnoreCase(数组[a+1][0].getLastName())>0))
临时=数组[a][b];
数组[a][b]=数组[a+1][0];
数组[a+1][0]=临时;
}
else if(b<2)
{if((数组[a][b].getLastName().CompareTIgnoreCase(数组[a][b+1].getLastName())>0))
临时=数组[a][b];
数组[a][b]=数组[a][b+1];
数组[a][b+1]=临时;
}
}
}//B循环结束
}//循环结束
//结束方法检查
看看你的代码格式!始终使用{}。
如果不使用曲线括号,则只有下一行取决于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。当发布这样的问题时,请包括课堂的最低版本(在本例中为学生)和一些测试数据。基本上是a。您可能需要解释管理该内部循环的标准。