华为机试 java_华为机试练习---java实现电话号码本
package huawei;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
/**
* java实现电话号码本
* @author USER
*
*/
public class Telephone {
public static void main(String[] args) {
HashMap map = new LinkedHashMap();
String[] info = null;
Scanner in = new Scanner(System.in);
String string = null;
while ((string = in.nextLine()) != null) {
info = string.split(" ");
String command = null;
String name = null;
String phone = null;
command = info[0];
switch (command) {
case "save":
name = info[1];
phone = info[2];
if (name.length()>20 || phone.length()>20 || map.containsKey(name) || map.containsValue(phone) || name.length()==0 || phone.length()==0) {
System.out.println("error");
}else {
map.put(name, phone);
System.out.println(name+" "+phone);
}
break;
case "getName":
phone = info[1];
//怎么从map值找关键字
Set set = map.keySet();
Iterator it = set.iterator();
if (map.containsValue(phone)) {
while (it.hasNext()) {
if (map.get(it.next()).equals(phone)) {
System.out.println(it.next());
}
}
}else {
System.out.println("error");
}
break;
case "getPhonenum":
name = info[1];
if (map.containsKey(name)) {
System.out.println(map.get(name));
}else {
System.out.println("error");
}
break;
case "delete":
name = info[1];
if (map.containsKey(name)) {
map.remove(name);//删除键值,也删除了对应的值
System.out.println("OK");
}else {
System.out.println("error");
}
break;
case "count":
if (map.size()>200) {
System.out.println("out of the max memory");
}else {
System.out.println(map.size());
}
break;
case "clear":
map.clear();
break;
case "display":
/*Set> mapset = map.entrySet();
Iterator> its = mapset.iterator();
while (its.hasNext()) {
Map.Entry entry = (Map.Entry) its.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key+":"+value);
}*/
Set sets = map.keySet();
for (String str : sets) {
System.out.println(str+":"+map.get(str));
}
break;
default:
System.out.println("error,please input again:");
break;
}
}
}
}