数组存对象方式实现随机点名小程序

[数组存对象方式实现随机点名小程序

/*一个随机点名系统,数组存对象方式实现,共随机10次,
输出抽中的学员以及抽中次数,萌新的作业题
*/
public class Student {
	private String name;
	private int count;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}
	public Student(String name, int count) {
		this.name = name;
		this.count = count;
	}
	public Student() {//无参构造有参构造都写上,养成习惯
		
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", count=" + count + "]";
	}
}	

上述是封装的方法,下面是测试类==

import java.util.Scanner;

public class Test {
	static Student names[] = new Student[5];
	static Scanner sc = new Scanner(System.in);

	public static void main(String[] args) {
		names[0] = new Student("张三", 0);
		names[1] = new Student("李四", 0);
		names[2] = new Student("王五", 0);
		names[3] = new Student("赵信", 0);
		names[4] = new Student("盖伦", 0);
		int index ; 
		String iscontinue;
		do {
			for (int i = 0; i < 10; i++) {
				index=(int) (Math.random() * names.length);
			Student name = names[index];// 抽中的学员
			System.out.println("本次被抽中学员是:" + name.getName());//使用数组的调用方法时要尤其注意空指针异常,看数组是否为空,这里是全赋值了的
			int num = name.getCount();// 调取原始抽中的次数
			name.setCount(num + 1);// 次数加一
			}
			
			
			
			System.out.println("是否重复抽取,重复请按Y,其他键退出");
			iscontinue = sc.next();
		} while ("y".equals(iscontinue));
		System.out.println("谢谢使用。。");
		for (Student name : names) {
			System.out.println(name.getName() + ":" + name.getCount());
		}
		sc.close();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值