【发布时间】:2018-04-23 14:50:47
【问题描述】:
我当前的 switch 语句集有效,但它们占用了太多行,我不确定如何创建一个工作循环来压缩 switch 语句。
这是我当前在一个方法中的 switch 语句(我有六个,以下加 1)
public static String convert (String str) {
String strb = new StringBuilder(str);
switch (str.charAt(4)) {
case 'a':
case 'b':
case 'c':
strb.insert(4, 2);
strb.deleteCharAt(5);
break;
case 'd':
case 'e':
case 'f':
strb.insert(4, 3);
strb.deleteCharAt(5);
break;
case 'g':
case 'h':
case 'i':
strb.insert(4, 4);
strb.deleteCharAt(5);
break;
case 'j':
case 'k':
case 'l':
strb.insert(4, 5);
strb.deleteCharAt(5);
break;
case 'm':
case 'n':
case 'o':
strb.insert(4, 6);
strb.deleteCharAt(5);
break;
case 'p':
case 'q':
case 'r':
case 's':
strb.insert(4, 7);
strb.deleteCharAt(5);
break;
case 't':
case 'u':
case 'v':
strb.insert(4, 8);
strb.deleteCharAt(5);
break;
case 'w':
case 'x':
case 'y':
case 'z':
strb.insert(4, 9);
strb.deleteCharAt(5);
break;
}
return strb.toString();
}
我尝试了一个 for 循环,但它似乎不起作用。有什么建议吗?
for (index = 4; index < str.length(); index++) {
switch (str.charAt(index)) {
case 'a':
case 'b':
case 'c':
strb.insert(index, 2);
strb.deleteCharAt(index + 1);
break;
case 'd':
case 'e':
case 'f':
strb.insert(index, 3);
strb.deleteCharAt(index + 1);
break;
case 'g':
case 'h':
case 'i':
strb.insert(index, 4);
strb.deleteCharAt(index + 1);
break;
case 'j':
case 'k':
case 'l':
strb.insert(index, 5);
strb.deleteCharAt(index + 1);
break;
case 'm':
case 'n':
case 'o':
strb.insert(index, 6);
strb.deleteCharAt(index + 1);
break;
case 'p':
case 'q':
case 'r':
case 's':
strb.insert(index, 7);
strb.deleteCharAt(index + 1);
break;
case 't':
case 'u':
case 'v':
strb.insert(index, 8);
strb.deleteCharAt(index + 1);
break;
case 'w':
case 'x':
case 'y':
case 'z':
strb.insert(index, 9);
strb.deleteCharAt(index + 1);
break;
}
}
【问题讨论】:
-
你声明
index变量了吗? -
在我的程序中,是的,我声明了 index 一个变量,但显然我忘了在这里添加
标签: java loops switch-statement stringbuilder