- import java.io.File;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.util.HashMap;
- import java.util.Random;
- import java.util.Scanner;
- import java.util.Set;
- /* 定义一个String数组str[]={“橙汁”,”雪碧”,”啤酒”,”二锅头”}用来代表喝的饮料
- 创建3个Student对象,从控制台获取属性值,
- 输入格式为:姓名,年龄。
- (利用有参构造赋值),将这3个对象存入到Map集合中(map<学生,要喝的饮料>),其中key是Student对象,
- 对应的value值需要随机(random)从str数组中获取,
- *
- * (如果Student对象的年龄不满18岁则不能喝酒,
- 如果获取到白酒或者啤酒则必须继续获取,直到获取到其它饮料为止)
- 将map中,所有信息写到当前项目Student_info.txt下
- *
- * */
- public class Test {
- public static void main(String[] args) throws IOException {
- // 定义字符串数组
- String[] str = { "橙汁", "雪碧", "啤酒", "二锅头" };
- Scanner sc = new Scanner(System.in);
- Random rd = new Random();
- // 创建学生对象
- System.out.println("请输入姓名和年龄");
- Student s1 = new Student(sc.nextLine(), sc.nextInt());
- System.out.println("请输入姓名和年龄");
- Student s2 = new Student(sc.next(), sc.nextInt());
- System.out.println("请输入姓名和年龄");
- Student s3 = new Student(sc.next(), sc.nextInt());
- // System.out.println(s1);
- HashMap<Student, String> hm = new HashMap<>();
- hm.put(s1, str[rd.nextInt(3)]);
- hm.put(s2, str[rd.nextInt(3)]);
- hm.put(s3, str[rd.nextInt(3)]);
- System.out.println(hm);
- Set<Student> set = hm.keySet();
- int count=0;
- String[] stringWriter = new String[3];
- for (Student s : set) {
- if (s.getAge() < 18)
- while (hm.get(s).equals("啤酒") || hm.get(s).equals("二锅头")) {
- hm.put(s, str[rd.nextInt(3)]);
- System.out.println(hm);
- }
- stringWriter[count]="学生的名字是:"+s.getName()+" 学生的年龄是:"+s.getAge()+" 学生爱喝的饮料是:"+hm.get(s);
- count++;
- }
- char[] arr=(stringWriter[0]+stringWriter[1]+stringWriter[2]).toCharArray();
- FileWriter fw=new FileWriter(new File("Student_info.txt"));
- fw.write(arr);
- fw.close();
- }
- }
复制代码 |
|