JAVA——学生信息输出

本文介绍了初学者如何使用Java实现一个包含20个学生的类,通过实例化对象调用方法。内容包括创建数组存储Student01对象,随机生成学号、年级和成绩,以及使用冒泡排序算法对学生成绩进行排序并打印相关信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

初学java,学到了面向对象,类内方法调用:要实例化本类,new一个本类对象,用本类对象去调用类内方法;

创建一个学生类,包含20个学生,学生学号1-20,输出学生信息,并打印相关学生信息,可查询相关年级学生,采用冒泡排序对学生成绩排序。

1.创建20个学生数组,类型为Student01类,即你所创建的类的类型数组;

2.在给数组赋值时要声明数组成员类型,数组里存储内容仍是你创建的类的类型;

3.冒泡排序时交换的内容是整个数组的成员,而不仅仅是分数

代码如下:

public class StudentTest01 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Student01[] stu = new Student01[20];//创建一个Student01类的数组
        StudentTest01 test = new StudentTest01();//调用奔雷的方法要实例化奔雷对象
        for(int i = 0;i < stu.length; i ++) {
            stu[i] = new Student01();//数组的成员内容是Student01类
            stu[i].num = i + 1;
            stu[i].state = (int)(Math.random() * (6 - 1 + 1) + 1);
            stu[i].score = (int)(Math.random() * (100 - 0 + 1) + 1);
        }
        System.out.println("********打印学生信息*********");
        test.print(stu);
        System.out.println("********打印查询年级学生信息*********");
        test.searchState(stu,4);
        System.out.println("********打印成绩排序后学生信息*********");
        test.sort(stu);
        test.print(stu);
    }
    public void print(Student01[] stu) {
        for(int i =0;i < stu.length;i ++) {
            System.out.println(stu[i].info());
        }
    }
    public void searchState(Student01[] stu,int state) {
        for(int i = 0;i <stu.length;i ++) {
            if(stu[i].state == state) {
                System.out.println(stu[i].info());
            }
        }
    }
    public void sort(Student01[] stu) {
        for(int i = 0;i < stu.length - 1;i ++) {
            for(int j = 0;j < stu.length - i - 1;j ++) {
                if(stu[j].score > stu[j + 1].score) {
                    Student01 temp = stu[j];//交换的是数组元素,Student01类中的内容
                    stu[j] = stu[j + 1];
                    stu[j + 1] = temp;
                }
            }
        }
    }

}
class Student01{
    int num;
    int score;
    int state;
    public String info() {
        return "学号:" + num + ",年级:" + state + ",成绩:" + score;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值