第六屆華爲創新杯編程大賽-----電話號碼本的設計



package contest;
import java.util.*;
import java.io.*;
public class Main 
{
	public static void main(String[] args) throws IOException
	{
		//用一個Map集合存儲電話本中的姓名和電話號碼
		HashMap<String, String> map = new LinkedHashMap<String, String>();		
		String[] info = null;
		
		//讀一行命令
		InputStream in = System.in;
		InputStreamReader isr = new InputStreamReader(in);
		BufferedReader bufr = new BufferedReader(isr);
		String line = null;
		while((line = bufr.readLine()) != null)
		{
			//將讀到的一行數據按空格符劃分
			info = line.split(" ");
			String command = info[0];
			String name = null;
			String phoneNum = null;
			
			switch (command)
			{
				case "save":
					name = info[1];
					phoneNum = info[2];
					if(map.containsKey(name) || map.containsValue(phoneNum) || name.length() >20 || phoneNum.length() > 20
						||	name.length() == 0 || phoneNum.length() == 0)
					{
						System.out.println("error");
					}else
					{
						map.put(name, phoneNum);
						System.out.println(name + " " + phoneNum);
					}				
					break;
	
				case "getName":
					phoneNum = info[1];
					//創建一個set集合存儲key值
					Set<String> mapSet = map.keySet();
					//創建一個mapSet的迭代器
					Iterator<String> iter = mapSet.iterator();
					if(map.containsValue(phoneNum))
					{
						//循環遍歷尋找鍵值是value值的key
						while(iter.hasNext())
						{
							String key = iter.next();
							if(map.get(key).equals(phoneNum))
							{
								System.out.println(key);
							}
						}
						
					}else
					{
						System.out.println("error");
					}
					break;
					
				case "getPhoneNum":
					name = info[1];
					if(map.containsKey(name))
					{
						String number = map.get(name);
						System.out.println(number);
					}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":
					int count = map.size();
					if(count > 200)
					{
						System.out.println("電話本中電話記錄數超過200!");
					}
					System.out.println(count);
					break;
				case "clear":
					map.clear();
					break;
				default:
					System.out.println("錯誤的命令,請重新輸入!");
					break;
			}
		}
		bufr.close();
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章