java入门小练习(对象数组)

类的使用和对象数组

问题描述:构建一个Student类,有属性学号,年级,成绩。

定义方法给学生学号赋值,随机赋予年级(1-6),随机赋予成绩。

能够遍历所有的学生信息;能够按年级查找学生信息;能够按照成绩进行排序

sort():排序操作

searchState():查找操作

print():遍历操作

首先给每个学生赋予学号,年级和成绩的信息

Student[] stus = new Student[20];
    for(int i = 0;i<stus.length;i++){
        stus[i] = new Student();
        stus[i].number = i + 1;
        stus[i].state = (int)(Math.random() * (6-1+1)+1);
        stus[i].score = (int)(Math.random() * (100-0+1));
    }

完整代码

package com.helloworld.java;

public class HelloWorld {
    public static void main(String[] args) {


    Student[] stus = new Student[20];
    for(int i = 0;i<stus.length;i++){
        stus[i] = new Student();
        stus[i].number = i + 1;
        stus[i].state = (int)(Math.random() * (6-1+1)+1);
        stus[i].score = (int)(Math.random() * (100-0+1));
    }
    HelloWorld test = new HelloWorld();

    test.print(stus);
    System.out.println("------------------------------------");
    test.searchState(stus, 4);
    System.out.println("------------------------------------");
    test.sort(stus);
    System.out.println("------------------------------------");
    test.print(stus);

    }

    public void print(Student[]  stus){
        for(int i = 0;i<stus.length;i++){
            System.out.println(stus[i].info());
        }
    }

    /**
     * @quthor JK
     * @data 2020.11.19
     * @param stus
     * @param state
     */
    public void searchState(Student[] stus, int state){
        for(int i = 0;i<stus.length;i++){
            if(stus[i].state == state){
                System.out.println(stus[i].info());
            }
        }
    }
    public void sort(Student[] stus){
        for(int i=0;i<stus.length-1;i++){
            for(int j =0;j<stus.length-i-1;j++){
                if(stus[j].score > stus[j+1].score){
                    Student temp = stus[j];
                    stus[j] = stus[j+1];
                    stus[j+1] = temp;
                }
            }
        }
    }

}

class Student{

    int number;//学号
    int state;//年级
    int score;//成绩

    public String info(){
        return "学号:" + number + "----" + "年级:"+state+ "----" + "成绩:"+score;
    }


}

该程序根据尚硅谷学习课程所编写,方便同样学习该视频的同学参考。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值