题解 | #简单密码# 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); } } }}