Java-对象数组

Java-对象数组

题目

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

提示:

  1. 生成随机数:Math.random(),返回值类型double。
  2. 四舍五入取整:Math.round(double d),返回值类型long。

代码如下:

package com.atguigu.ace;

public class StudentAce
{
	public static void main(String[] args)
	{
		Student[] s1 = new Student[20];
		
		for(int i = 0; i < s1.length; i++)
		{
			s1[i] = new Student();
		    //学号
			s1[i].number = i + 1;
			//年级[1,6]
			s1[i].state = (int) (Math.random() * (6 - 1 + 1) + 1);
			//成绩[0,100]
			s1[i].score = (int) (Math.random() * (100 - 0 + 1) + 0);
		}
		
		StudentAce ace = new StudentAce();
		
		//1.遍历Student数组
		ace.print(s1);
		
		System.out.println("********************");
		
		//2.问题一:打印出3年级(state值为3)的学生信息
		ace.searchState(s1, 3);
		
		System.out.println("********************");
		
		//3.问题二:使用冒泡排序按学生成绩排序,并遍历所有学生信息
		ace.bubbleSort(s1);
		ace.print(s1);
	}
	
	/**
	 * 
	 * @Description   遍历Student数组
	 * @author Shadowckr  
	 * @date 2021年3月21日下午3:27:55  
	 * @param s1
	 */
	public void print(Student[] s1)
	{
		for(int i = 0; i < s1.length; i++)
		{
			System.out.println(s1[i].info());
		}
	}
	
	/**
	 * 
	 * @Description   查找Student数组中指定年级的学生信息
	 * @author Shadowckr  
	 * @date 2021年3月21日下午3:22:50  
	 * @param s1
	 * @param state
	 */
	public void searchState(Student[] s1, int state)
	{
		for(int i = 0; i < s1.length; i++)
		{
			if(s1[i].state == state)
			{
				System.out.println(s1[i].info());
			}
		}
	}
	
	/**
	 * 
	 * @Description   冒泡排序,给Student数组排序
	 * @author Shadowckr  
	 * @date 2021年3月21日下午3:12:34  
	 * @param s1
	 */
	public void bubbleSort(Student[] s1)
	{
		for(int i = 0; i < s1.length - 1; i++)
		{
			for(int j = 0; j < s1.length - i - 1; j++)
			{
				//按成绩从小到大排序
				if(s1[j].score > s1[j+1].score)
				{
					Student temp = s1[j];
					s1[j] = s1[j+1];
					s1[j+1] = temp;
				}
			}
		}
			
	}
}

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

注意:
在这里插入图片描述
此代码将操作数组的功能封装到方法中。

Math.random()是返回[0,1)之间的随机数,包括0但是不包括1。
在这里插入图片描述

生成区间[a,b]之间的随机数公式为:

int value = (int)(Math.random() * (b - a + 1) + a);
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值