java - 冒泡排序二维数组按字母顺序Java
问题描述
我能否得到第二双眼睛来告诉我为什么我的数组每次打印时都没有被排序?我正在尝试对 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
解决方案
看看你的代码格式!始终使用 {}。如果您不使用弯括号,则仅下一行取决于 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
自动格式化。
推荐阅读
- mysql - 从不同的表中获取复杂的数据
- google-bigquery - 将字符串数组转换为单行值
- c - 从 arduino 接收和发送数据到 stml476RG
- reactjs - 如何使用 updateQuery 编写测试 react-apollo 组件来更新查询
- ios - UIView 捕捉单指动作,但发送两指捏合以查看后面
- ruby - Cocoapod 安装后直接获取主项目
- ios - Xcode 在某些视图上显示空的蓝色矩形而不是对象
- html - 为什么 CSS 悬停菜单在移动设备上不起作用?
- javascript - 如何使用我的正则表达式捕获可选星号?
- javascript - 按顺序从图像中返回数据