初学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;
}
}