/*时间28分钟
* 注意,自定义对象,一定要传比较器,一定要在随机加上无限循环
* String[] str = {"奶昔","加多宝","啤酒","白酒"};//饮料
* 1.建立一个人类,有姓名和年龄属性
* 2. 键盘输入3个对象,有用有参构造存入到对象中
* 2.5 随机生成一个数 获取饮料类型
* 3.建立一个集合 健存对象,值存饮料
* 4.年龄小于18岁的不能获取酒类.
* 5.最后把这些数据写到文件中,格式: 姓名: 年龄: 饮料:
* */
public class 集合_IO_多线程_加多宝_白酒 {
static int index;
public static void main(String[] args) throws IOException {
String[] str = {"奶昔","加多宝","啤酒","白酒"};
Scanner sc = new Scanner(System.in);
TreeMap<Person,String> tm = new TreeMap<Person, String>(new Comparator<Person>() {
public int compare(Person p1, Person p2) {
int num =p1.getAge()-p2.getAge();
return num==0?1:num;
}
});
Random r = new Random();
System.out.println("请输入姓名和年龄 逗号分隔");
for (int i = 0; i <3; i++) {
String str1 = sc.nextLine();
String [] arr = str1.split(",");
Person p = new Person(arr[0],Integer.parseInt(arr[1]));
//int index=-1;
while(true){
index = r.nextInt(3);
if((p.getAge()<18 && index==3)||(p.getAge()<18) && index==2 ){
continue;
}else{
//System.out.println(index);
break;
}
}
tm.put(p, str[index]);
//System.out.println(p.getName()+" "+p.getAge()+str[index]);
}
//将当前信息全部写到当前文件中,person.info.txt 格式:姓名:年龄:饮料
BufferedWriter bw = new BufferedWriter(new FileWriter("person.info.txt"));
for (Map.Entry<Person,String> me:tm.entrySet()) {
bw.write("姓名:"+me.getKey().getName()+" 年龄:"+me.getKey().getAge()+" 饮料:"+me.getValue());
//bw.write("1111");
bw.newLine();
}
bw.close();
System.out.println("书写成功!!!");
}
}
class Person{
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = 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() {
super();
}
}
/*张三,15
* 李四,17
* 王五,25
*
* */
|
|