第二题面试时候的答案,还有结束后自己再重新做的答案
面试时候的答案(错误回答):(在限时的情况下,脑子真的会抽。。。。)
public static void main(String[] args) throws IOException {
String[] drink ={"奶昔","加多宝","啤酒","白酒"};
Person a = new Person("张三",12);
Person b = new Person("李四",14);
Person c = new Person("王五",18);
HashMap<Person,String> mp = new HashMap<>();
method(a,mp);
method(b,mp);
method(c,mp);
/*Iterator it = mp.keySet().iterator();
while(it.hasNext())
{
Person key = (Person) it.next();
System.out.println(key+mp.get(key));
}*/
FileWriter fw = new FileWriter("person_info.txt");
BufferedWriter bw = new BufferedWriter(fw);
for (Person p : mp.keySet()) {
System.out.println(p+mp.get(p));
String per = String.valueOf(p);
String mps =mp.get(p);
System.out.println(per);
String perall =per+mps;
System.out.println(perall);
bw.write(perall);
bw.newLine();
}
bw.close();
}
public static void method(Person p,HashMap<Person,String> mp){
Random r = new Random();
int n = r.nextInt(4);
String[] drink ={"奶昔","加多宝","啤酒","白酒"};
mp.put(p, drink[n]) ;
if(p.age<18&(drink[n]==("白酒")||drink[n]=="啤酒")){
mp.remove(p);
}
if(!mp.containsKey(p)){
method(p,mp);
}
}
}
class Person implements Comparable{
String name;
int age;
public Person() {
super();
}
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;
}
@Override
public String toString() {
return "姓名" + name + ": 年龄" + age+":" ;
}
}
======================================考完回去自己写的
public static void main(String[] args) throws IOException {
Person p1 = new Person("zhangsan",26);
Person p2 = new Person("lisi",14);
Person p3 = new Person("Wangwu",15);
String[] str ={"奶昔","加多宝","啤酒","白酒"};
HashMap<Person,String> tm = new HashMap<Person, String>();
getDrink(p1, str, tm);
getDrink(p2, str, tm);
getDrink(p3, str, tm);
BufferedWriter br = new BufferedWriter(new FileWriter("PersonDrink.txt"));
for (Person p : tm.keySet()) {
br.write(p.toString() +":" +tm.get(p));
br.newLine();
}
for (Person p : tm.keySet()) {
System.out.println(p.toString() +":" +tm.get(p));
}
br.close();
}
public static void getDrink(Person p1, String[] str,
HashMap<Person, String> tm) {
Random r = new Random();
int num = r.nextInt(4);
tm.put(p1, str[num]);
if (p1.getAge()<18) {
while(tm.get(p1)=="啤酒"||tm.get(p1)=="白酒") {
num = r.nextInt(4);
tm.put(p1, str[num]);
}
}
}
}
class Person{
String name;
int age;
Person() {
}
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;
}
@Override
public String toString() {
return name + ":"+age;
}
} |