import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Scanner;
public class Test111 {
public static void main(String[] args) throws Exception {
String[] str={"奶昔","啤酒","加多宝","白酒"};
HashMap<Person, String> map=new HashMap<>();
Scanner scanner=new Scanner(System.in);
while (map.size()<4) {
try {
System.out.println("请输入第个"+(map.size()+1)+"学生的信息,格式为姓名,年龄");
String mes=scanner.nextLine();
Person person=new Person(mes.split(",")[0], Integer.parseInt(mes.split(",")[1]));
map.put(person, randomValue(person.getAge(), str));
} catch (Exception e) {
System.out.println("输入信息不合法,请对照格式输入");
//e.printStackTrace();
}
}
BufferedWriter writer=new BufferedWriter(new FileWriter("person-info.txt"));
for (Entry<Person, String> entry : map.entrySet()) {
String info="姓名:"+entry.getKey().getName()+":"+entry.getKey().getAge()+":"
+entry.getValue();
writer.write(info);
writer.newLine();
}
writer.close();
}
//根据年龄获取随机值
public static String randomValue(int age,String[] str){
Random rd=new Random();
int index=rd.nextInt(4);
if (age<18) {
//只能喝饮料,
while(str[index].equals("啤酒")||str[index].equals("白酒")){
index=rd.nextInt(4);
}
}else {
//否则可以和所有饮料
index=rd.nextInt(4);
}
return str[index];
}
}
class Person{
private String name;
private int age;
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 Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
}
|