题解 | #简单密码# Java HashMap遍历器实现

public class Algorithm {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        char[] chars = input.toCharArray();
        HashMap<String, Integer> hm = new HashMap<>();
        hm.put("abc", 2);
        hm.put("def", 3);
        hm.put("ghi", 4);
        hm.put("jkl", 5);
        hm.put("mno", 6);
        hm.put("pqrs", 7);
        hm.put("tuv", 8);
        hm.put("wxyz", 9);
        for (char c : chars){
            if (c >= 'A' && c <= 'Z'){
                if ((c + 32) == 'z'){
                    System.out.print('a');
                }else{
                    System.out.print((char)(c + 33));
                }
            }else if(c >= 'a' && c <= 'z'){
                Character cc = c;
                Iterator<Map.Entry<String, Integer>> myIt = hm.entrySet().iterator();
                while (myIt.hasNext()){
                    Map.Entry<String, Integer> m = myIt.next();
                    if (m.getKey().contains(cc.toString())){
                        System.out.print(m.getValue());
                        break;
                    }
                }
            }else{
                System.out.print(c);
            }
        }
    }
}

可以使用HashMap遍历器方法来解题

public class Algorithm {    public static void main(String[] args){        Scanner sc = new Scanner(System.in);        String input = sc.nextLine();        char[] chars = input.toCharArray();        HashMap<String, Integer> hm = new HashMap<>();        hm.put("abc", 2);        hm.put("def", 3);        hm.put("ghi", 4);        hm.put("jkl", 5);        hm.put("mno", 6);        hm.put("pqrs", 7);        hm.put("tuv", 8);        hm.put("wxyz", 9);        for (char c : chars){            if (c >= 'A' && c <= 'Z'){                if ((c + 32) == 'z'){                    System.out.print('a');                }else{                    System.out.print((char)(c + 33));                }            }else if(c >= 'a' && c <= 'z'){                Character cc = c;                Iterator<Map.Entry<String, Integer>> myIt = hm.entrySet().iterator();                while (myIt.hasNext()){                    Map.Entry<String, Integer> m = myIt.next();                    if (m.getKey().contains(cc.toString())){                        System.out.print(m.getValue());                        break;                    }                }            }else{                System.out.print(c);            }        }    }}
全部评论

相关推荐

完美的潜伏者许愿简历...:隐藏信息被你提取出来了,暗示,这就是暗示
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务