要求:
使用对象数组进行点名;
package com.qf.ng.homework;
public class Person {
private String name;
private int age;
private int count;
public Person(String name, int age, int count) {
this.name = name;
this.age = age;
this.count = count;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", count=" + count +
'}';
}
}
package com.qf.ng.homework;
import java.util.Random;
import java.util.Scanner;
//使用对象,优化点名系统
public class Demo01 {
public static void main(String[] args) {
Person[] people = creatArray(10);
start(people);
}
//创建对象数组
public static Person[] creatArray(int num) {
Person[] person = new Person[num];
Random random = new Random();
for (int i = 0; i < num; i++) {
int age = random.nextInt(30);
person[i] = new Person(i + 1 + "号同学", age, 0);
}
return person;
}
//输出学生的所有信息
public static void printAll(Person[] people) {
for (int i = 0; i < people.length; i++) {
System.out.println(people[i].toString());
}
}
//点名系统(只点一次)
public static void check(Person[] people) {
int num = 0; //表示被抽到的同学
int sum = people.length; //数组的长度
Random random = new Random();
num = random.nextInt(sum) + 1;//抽到的学号
people[num - 1].setCount(people[num - 1].getCount() + 1);//把学生被点到的次数加1 (为什么不能用++?)
System.out.println(num + "号同学被抽到了!"); //“++”的使用前提是可以直接使用该变量
System.out.println(people[num - 1].toString()); //但是count变量是private的(即不能直接使用),所以只能使用+1而不是++
}
public static void start(Person[] people) {
Scanner scanner = new Scanner(System.in);
boolean flag = true;
while (flag) {
table();
int choice = scanner.nextInt();
switch (choice) {
case 1:
check(people);
break;
case 2:
printAll(people);
break;
case 3:
System.out.println("感谢使用!!!");
flag = false; //注意要先把flag设置为false,否则会继续从while开始死循环
break;
}
}
}
//列表
public static void table() {
System.out.println("=============================================");
System.out.println("==================1.点名=====================");
System.out.println("==============2.看点名情况===================");
System.out.println("====================3.退出===================");
System.out.println("=============================================");
System.out.println("请按下数字进行选择:");
}
}