Java对象数组之对象数组题目Student类

问题描述

定义类Student,包含三个属性:学号number(int),年级state(int) ,成绩score(int)。创建20个学生对象,学号为1到20号,年级和成绩都由随机数确定。
问题1:打印出3年级(state值为3)的学生信息。
问题2:使用冒泡排序按学生成绩排序,并遍历所有学生信息。

创建Student类:

public class Student {
	
      int number;  //学号
      int state;   //年级
      int score;   //成绩
	public int getNumber() {
		return number;
	}
	public void setNumber(int number) {
		this.number = number;
	}
	public int getState() {
		return state;
	}
	public void setState(int state) {
		this.state = state;
	}
	public int getScore() {
		return score;
	}
	public void setScore(int score) {
		this.score = score;
	}
	
	public String info() {  //显示学生信息
		return ("学号:"+this.number+",年级"+this.state+",成绩"+this.score);
		
	}
        	
	}
	

创建类Stu_test:

    
import java.lang.Math;
public class Stu_test {
	        public static void main(String [] args) {
	        	
	        	Student[] stu = new Student[20];  //创建20个学生对象
	        	Stu_test test =  new Stu_test();  //创建类对象调用封装的方法
        	for(int i=0;i<stu.length;i++) {  //数组元素赋值
	        		stu[i] = new Student();
		        	stu[i].number=(i+1);
		        	stu[i].state = (int)(Math.random()*(6-1+1)+1);  //年级[1,6]
		        	stu[i].score = (int)(Math.random()*(100-0+1));  //成绩[0,100]
             
	        	}
	        
          
        	System.out.println("************问题一************");//问题一
           test.Print(stu);
           test.search(stu, 3);
	     
	       
	       System.out.println("*************问题二***********");  //问题一
           
	       //使用冒泡排序按学生成绩排序并遍历学生信息
	       test.Order(stu);
	       test.Print(stu);
	   
	      
	}
	        
	        //將方法進行封裝  
	        public void search(Student stu[],int state) {
		   		for(int j=0;j<20;j++) {  //打印3年级的学生信
		      		 System.out.println();
		      		if (stu[j].state==3) {
		          	System.out.println(stu[j].info());
		   			}
		      		
		      	}
		    }
	        
	    	public void Order (Student[] stu) {
	    	    //使用冒泡排序按学生成绩排序并遍历学生信息
	    	       for(int i = 0; i<stu.length-1;i++) {
	    	    	   for(int j=0;j<stu.length-1-i;j++) {
	    	    		   if(stu[j].score>=stu[j+1].score) {
	    	    			   Student temp = stu[j];  
	    	    			   // 交换的是学生这个对象而不是交换他们的成绩
	    	    			   stu[j]=stu[j+1];
	    	    			   stu[j+1]=temp;
	    	    		   }
	    	    	   }
	    	       }
	    	   
	    	}
	    	
	    	public void Print(Student[] stu) {  //遍历学生信息
	    		for(int j=0;j<20;j++) {  //打印所有年级的学生信息
	            	System.out.println(stu[j].info());
	    			}
	    	}
	    		
	        
}
  • 5
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值