public class StudentTest2 {
public static void main(String[] args) {
//创建20个学生对象的数组:
Student[] std = new Student[20];
for(int i = 0;i < std.length;i++) {
//给数组每个元素赋值:
std[i] = new Student();
//给Student对象的属性赋值,学号为1~20:
std[i].number = (i+1);
//年级Math.random[0.0 1.0)*6-->[0.0 6.0)-->(int)[0 6)+1-->[1 6]
std[i].state = (int)(Math.random()*6) + 1;
//成绩[0 100]
std[i].score = (int)(Math.random()*100) + 1;
}
Student stud = new Student();
//遍历20个学生的属性信息:
stud.arrayergo(std);
System.out.println("------------------------");
//问题一:打印出3年级(state值为3)的学生信息:
stud.statefind(std, 3);
System.out.println("------------------------");
//问题二:使用冒泡排序按学生成绩排序,并遍历所有学生信息:
for(int i = 0; i < std.length-1;i++) {
for(int j = 0;j < std.length-1-i;j++) {
if (std[j].score > std[j].score + 1) {
Student temp = std[j];
std[j] = std[j + 1];
std[j + 1] = temp;
}
}
}
for(int i = 0;i < std.length;i++){
System.out.println(std[i].info());
}
}
}
//定义类Student:
class Student{
//包含三个属性:
int number;//学号
int state;//年级
int score;//成绩
//显示学生属性信息方法:
public String info() {
return "学号:"+number+"\t"+"年级:"+state+"\t"+"成绩:"+score;
}
/**
*
* @Description 遍历Student数组的操作
* @author Free red
* @date 2021年7月14日下午11:10:27
* @param std 要遍历的数组
*/
public void arrayergo(Student[] std) {
for(int i = 0;i < std.length;i++){
System.out.println(std[i].info());
}
}
/**
*
* @Description 查找Student数组中指定年级的学生信息
* @author Free red
* @date 2021年7月14日下午11:04:39
* @param std 要查找的数组
* @param state 要查找的年级
*/
public void statefind(Student[] std,int state) {
for(int i = 0;i < std.length;i++) {
if(std[i].state==state) {
System.out.println(std[i].info());
}
}
}
/**
*
* @Description 使用冒泡排序按学生成绩排序,并遍历Student数组中所有学生信息
* @author dreamer
* @date 2021年7月16日下午3:08:29
* @param std 要排序的数组
*/
public void bubblesort(Student[] std) {
for(int i = 0; i < std.length-1;i++) {
for(int j = 0;j < std.length-1-i;j++) {
if (std[j].score > std[j].score + 1) {
Student temp = std[j];
std[j] = std[j + 1];
std[j + 1] = temp;
}
}
}
}
}

为什么运行后冒泡排序没有效果呢?
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
3条回答 默认 最新
- fql4818 2021-07-16 16:47关注
26行错了吧,值加1?应该是中括号中加1吧,另外,冒泡排序效率低,用 Collections.sort();方法比较好。
if (std[j].score > std[j].score + 1) {
修改成
if (std[j].score > std[j+1].score) {本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报