1 package com.atguigu.exer; 2 3 public class StudentTest { 4 5 public static void main(String[] args){ 6 7 Student[] stud = new Student[20];//定义对象数组 8 for(int i = 0;i < stud.length;i++){ 9 stud[i] = new Student();//给对象数组赋值 10 //给类元素赋值 11 stud[i].number = i + 1; 12 stud[i].score = (int)(Math.random() * 101); 13 stud[i].state = (int)(Math.random() * 6 + 1); 14 } 15 16 for(int i = 0;i < stud.length;i++){ 17 if(stud[i].state == 3){ 18 System.out.println(stud[i].info()); 19 } 20 } 21 System.out.println("************"); 22 //冒泡排序 23 for(int i = 0;i < stud.length - 1;i++){ 24 for(int j = 0;j < stud.length - 1 - i;j++){ 25 if(stud[j].score > stud[j+1].score){ 26 //交换两个对象,而不是交换两个分数(属性) 27 Student temp = stud[j]; 28 stud[j] = stud[j+1]; 29 stud[j+1] = temp; 30 } 31 } 32 } 33 //遍历 34 for(int i = 0;i < stud.length;i++){ 35 System.out.println(stud[i].info()); 36 } 37 38 } 39 } 40 41 class Student{ 42 43 int number; 44 int state; 45 int score; 46 47 public String info(){ 48 return "年级:" + state + " 学号:" + number + " 成绩:" + score; 49 } 50 51 }
原文:https://www.cnblogs.com/yzyjava/p/14364208.html