【Java例题】5.5 映射类的使用


5.映射类的使用。
使用HashMap保存英文-中文对照单词词典。
单词词典可以增加和删除词汇。
输入一个英文单词,翻译成中文并显示。
输入一个中文单词,翻译成英文并显示。

package chapter6;
import java.util.*;

public class demo5 {
    static public void main(String[] args) {
        Map<String, String> CtoE=new HashMap<String, String>();
        Map<String, String> EtoC=new HashMap<String, String>();
        Scanner sc=new Scanner(System.in);
        while(true) {
            System.out.println("按1+enter-----添加词汇");
            System.out.println("按2+enter-----删除词汇");
            System.out.println("按3+enter-----英文译中");
            System.out.println("按4+enter-----中文译英");
            System.out.println("按0+enter-----结束进程");
            int con1=sc.nextInt();
            if(con1==0) {
                System.out.println("系统已退出");
                break;
            }
            switch(con1) {
                case 1:    System.out.println("请输入要加的英文单词");
                        String Eng=sc.next();
                        System.out.println("请输入该单词的中文");
                        String Chi=sc.next();
                        CtoE.put(Chi,Eng);
                        EtoC.put(Eng,Chi);
                        break;
                case 2:    System.out.println("请输入要删的英文单词");
                        String Eng1=sc.next();
                        CtoE.remove(EtoC.get(Eng1));
                        EtoC.remove(Eng1);
                        System.out.println("删除成功");
                        break;
                case 3:    System.out.println("请输入英文单词");
                        String Eng2=sc.next();
                        System.out.println(Eng2+"的中文:"+EtoC.get(Eng2));
                        break;
                case 4:    System.out.println("请输入中文翻译");
                        String Chi1=sc.next();
                        System.out.println(Chi1+"的英文:"+CtoE.get(Chi1));
                        break;
                default:System.out.println("请输入正确指令!");
                        break;
            }
        }
    sc.close();
    }
}

猜你喜欢

转载自www.cnblogs.com/LPworld/p/10724081.html