题目: 定义类Student,包含三个属性:学号number(int),年级state(int),成绩score(int)。 创建20个学生对象,学号为1到20,年级和成绩都由随机数确定。
要求:
1.打印出3年级(state值为3)的学生信息。
2.使用冒泡排序按学生成绩排序,并遍历所有学生信息
代码:
package com.qihang;
public class StudentTest {
public static void main(String[] args) {
// 创建20个学生对象,对象数组
Student[] stus = new Student[20];
for(int i = 0; i<stus.length; i++) {
// 给数组元素赋值!
stus[i] = new Student();
// 给对象的对应属性赋值
// 学号
stus[i].number = (i + 1);
// 年级【1-6】 公式(b-a+1)+a
stus[i].state = (int)(Math.random()*(6-1+1)+1);
// 成绩 【0-100】
stus[i].score = (int)(Math.random()*(100-0+1));
}
//遍历学生数组
for(int i = 0; i<stus.length; i++) {
//System.out.println(stus[i]);//此时打印的是对应地址
System.out.println(stus[i].number+ ","+stus[i].state+","+stus[i].score);
}
//问题1
for(int i = 0; i<stus.length; i++) {
if(stus[i].state == 3) {
System.out.println(stus[i].info());
}
}
//问题2 冒泡排序--按学生成绩排序
for(int i = 0; i<stus.length-1; i++) {
for(int j = 0; j<stus.length-1-i; j++) {
if(stus[j].score > stus[j+1].score) {
// 注意交换对象,而非成绩
Student temp = stus[j];
stus[j] = stus[j+1];
stus[j+1] = temp;
}
}
}
//遍历学生数组
for(int i = 0; i<stus.length; i++) {
//System.out.println(stus[i]);//此时打印的是对应地址
System.out.println(stus[i].number+ ","+stus[i].state+","+stus[i].score);
}
}
}
class Student{
int number;//学号
int state;//年级
int score;//成绩
// 定义显示信息的方法
public String info() {
return "学号:"+number+",年级: "+state+",成绩:"+score;
}
}
结果1:
结果2: