类的使用和对象数组
问题描述:构建一个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;
}
}
该程序根据尚硅谷学习课程所编写,方便同样学习该视频的同学参考。