[数组存对象方式实现随机点名小程序
/*一个随机点名系统,数组存对象方式实现,共随机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();
}
}