创建一个Student类,属性有2个,分别是:name(String类型),age(int类型)
定义一个String数组str[]={"鲜橙多","可乐","雪碧","二锅头","啤酒","红酒"}用来代表喝的饮料
创建3个Student对象,从控制台获取属性值,输入格式为:姓名,年龄(利用有参构造赋值),
将这3个对象存入到Map集合中(map<学生,要喝的饮料>),其中key是Student对象,
对应的value值需要随机(random)从str数组中获取,如果Student对象的年龄不满18岁则不能喝酒,将map中,所有信息打印到控制台。
------------------------------------------------------------------------------------------------------------------------------
package zuooye;
import java.util.HashMap;
import java.util.Random;
import java.util.Scanner;
public class Text06 {
public static void main(String[] args) {
String[] str = { "鲜橙多", "可乐", "雪碧", "二锅头", "啤酒", "红酒" };
HashMap<Student, String> hm = new HashMap<>();
Scanner sc = new Scanner(System.in);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 3; i++) {
String st = sc.nextLine();
sb.append(st + ",");
}
String[] arr = sb.toString().split("\\,");
for (String st : arr) {
System.out.println(st);
}
Random r = new Random();
for (int i = 0; i < arr.length; i += 2) {
int num = 0;
String drink = "";
if (Integer.parseInt(arr[i + 1]) < 18) {
num = r.nextInt(3);
drink = str[num];
} else {
num = r.nextInt(6);
drink = str[num];
}
hm.put(new Student(arr[i], Integer.parseInt(arr[i + 1])), drink);
}
for (Student g : hm.keySet()) {
System.out.println(g + "喝" + hm.get(g));
}
}
}
|
|