我今天刚看到我的一些作品,我想让用户输入他们想要的字母数量并继续转换。我能帮忙吗?太棒了。我尝试了什么。我是java编程的新手,这就是原因。谢谢:)
这是我的整个编程
import java.util.Scanner;
public class Try2 {
public static void main(String[] args) {
int counter = 0;
int it = 0;
Scanner keyboard = new Scanner(System. in );
System.out.println("Enter words to digits: ");
String alpha = keyboard.nextLine();
alpha = alpha.toLowerCase();
String num = (" ");
while (counter < alpha.length()) {
switch (alpha.charAt(it)) {
case 'A':
case 'a':
case 'B':
case 'b':
case 'c':
case 'C':
num += "2";
counter++;
break;
case 'D':
case 'E':
case 'F':
case 'd':
case 'e':
case 'f':
num += "3";
counter++;
break;
case 'G':
case 'H':
case 'I':
case 'g':
case 'h':
case 'i':
num += "4";
counter++;
break;
case 'J':
case 'K':
case 'L':
case 'j':
case 'k':
case 'l':
num += "5";
counter++;
break;
case 'M':
case 'N':
case 'O':
case 'm':
case 'n':
case 'o':
num += "6";
counter++;
break;
case 'P':
case 'R':
case 'S':
case 'p':
case 'r':
case 's':
num += "7";
counter++;
break;
case 'T':
case 'U':
case 'V':
case 't':
case 'u':
case 'v':
num += "8";
counter++;
break;
case 'W':
case 'w':
case 'X':
case 'x':
case 'Y':
case 'y':
case 'Z':
case 'z':
case ' ':
num += "9";
counter++;
break;
}
if ((counter % 4) == 3) {
num += "-";
}
it++;
}
System.out.println(num);
}
}
答案 0 :(得分:0)
您可以使用另一个while
循环包装读取的行代码:
Scanner keyboard = new Scanner(System.in);
while(true) {
System.out.println("Enter words to digits: ");
String alpha = keyboard.nextLine();
alpha = alpha.toLowerCase();
String num = " ";
int counter = 0;
int it = 0;
while (counter < alpha.length()) {
...
}
//new line (optional)
num += "\n";
}
您可以检查用户是否输入了一个标志来结束输入:
//You can choose any flag you want
if(alpha.equals("finish")) {
break;
}
关于您的开关:
alpha = alpha.toLowerCase();
alpha
不匹配:[a-zA-z ]
(仅包含字母和空格),IndexOutOfBoundsException
会抛出alpha.charAt(it)
,因为您不会增加counter
并且循环不会及时退出。 要防止出现上一个问题,您可以删除counter
和it
并将while
循环更改为for
循环:
for (int i = 0; i < alpha.length(); i++) {
if ((i % 4) == 3) {
num += "-";
}
switch (alpha.charAt(i)) {
...
}
}