/*需求:
创建一个Student类(name,age), 定义一个String数组str[]={"橙汁","雪碧","啤酒","二锅头","可乐","红茶"}用来代表喝的饮料,
键盘录入三个学生的信息,格式为:姓名,年龄 , 通过Student类的有参构造将其封装成学生对象,然后将这3个对象存入
到Map集合中( map<学生,要喝的饮料>),其中key是Student对象,对应的value值需要随机(random)从str数组中获取,
要求: 如果Student对象的年龄不满18岁则不能喝酒,如果获取到白酒或者啤酒则必须继续获取,直到获取到其它饮料为止*/
import java.util.HashMap;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
public class Deom05 {
public static void main(String[] args) {
String str[] = {"橙汁", "雪碧", "啤酒", "二锅头", "可乐", "红茶"};
HashMap<Student, String> map = new HashMap<>();
for (int i = 0; i < 3; i++) {
Student student = addStudent();
int chose = chose(str, student);
map.put(student, str[chose]);
}
Set<Student> keySet = map.keySet();
for (Student key : keySet) {
String name = key.getName();
int age = key.getAge();
String drink = map.get(key);
System.out.println(name + "," + age + "," + drink);
}
}
public static Student addStudent() {
Scanner sc = new Scanner(System.in);
System.out.println("请输入学生姓名");
String name = sc.next();
System.out.println("请输入学生年龄");
int age = sc.nextInt();
Student student = new Student(name, age);
return student;
}
public static int chose(String[] str, Student student) {
Random random = new Random();
int i = random.nextInt(6);
if (student.getAge() <=18) {
while (str[i].equals("啤酒") || str[i].equals("二锅头")) {
i = random.nextInt(6);
}
} else {
i = random.nextInt(6);
}
return i;
}
}
Map
最新推荐文章于 2022-07-13 16:06:00 发布