该程序应该将相应的数字输出到用户输入的字符串,并且应该允许用户继续输入字符串直到它们输入空字符串。我已经设法获得的循环部分和第一个输出到第一个输入是正确的但我遇到的问题是从第二个输入开始,程序只显示第一个输出。像这样:
以字母输入您的电话号码:致电bome(输入)
您的电话号码是:225-52663(输出)
用信件输入您的电话号码:获得贷款
您的电话号码是:225-52663
如果有人可以帮我解决这个问题,我将非常感激!
String teleLetter,teleNum="";
int i=0;
do
{
System.out.println("Enter your telephone number in letters: "); //ask user
to input telephone number in letter
teleLetter = keyboard.nextLine();
char teleChar;
while(i<teleLetter.length()) //condition to read till end of teleletter then stop program
{
teleChar = teleLetter.charAt(i); //take all the char individually from string
switch(teleChar) //ensure that each letter correspond to a number
{
//to ensure lowercase and uppercase
case 'a':
case 'A':
case 'b':
case 'B':
case 'c':
case 'C':
teleNum = teleNum+2; //assign telenum
break;
case 'd':
case 'D':
case 'e':
case 'E':
case 'f':
case 'F':
teleNum=teleNum+3;
break;
case 'g':
case 'G':
case 'h':
case 'H':
case 'i':
case 'I':
teleNum=teleNum+4;
break;
case 'j':
case 'J':
case 'k':
case 'K':
case 'l':
case 'L':
teleNum=teleNum+5;
break;
case 'm':
case 'M':
case 'n':
case 'N':
case 'o':
case 'O':
teleNum=teleNum+6;
break;
case 'p':
case 'P':
case 'q':
case 'Q':
case 'r':
case 'R':
case 's':
case 'S':
teleNum=teleNum+7;
break;
case 't':
case 'T':
case 'u':
case 'U':
case 'v':
case 'V':
teleNum=teleNum+8;
break;
case 'w':
case 'W':
case 'x':
case 'X':
case 'y':
case 'Y':
case 'z':
case 'Z':
teleNum=teleNum+9;
break;
case ' ':
break;
default:
System.out.println("Invalid digit!");
break;
}
if(i==2) //at the second loop
{
teleNum=teleNum+'-';
}
i++;
}
if(teleLetter.length() == 0) //if the input is null, print invalid message
{
System.out.println("Invalid as nothing is entered!");
}
else
{
System.out.println("Your telephone number is: "+teleNum); // output telephone number to user
}
}while(!teleLetter.isEmpty());
}
}
答案 0 :(得分:0)
您没有重置&#39;我导致您的第二个while循环直接失败,因为&#39; i&#39;已经是&gt; =&#39; teleLetters.length()&#39;。试试这种方式:
if(teleLetter.length() == 0) //if the input is null, print invalid message
{
System.out.println("Invalid as nothing is entered!");
}
else
{
System.out.println("Your telephone number is: "+teleNum); // output telephone number to user
i = 0;
}