我正在编写程序将电话号码中的字母转换为相应的数字,除了某些格式外,它几乎完成了:
import java.util.Scanner;
public class PhoneKeypad
{
public static void main (String [] args)
{
Scanner scan = new Scanner (System.in);
String number;
int currentChar;
char character;
int finalNumber;
int getNumber;
int start;
String end;
currentChar = 0;
do
{
System.out.print ("\nEnter a phone number with letters: ");
number = scan.nextLine();
number = number.toUpperCase();
while (currentChar < number.length())
{
character = number.charAt(currentChar);
finalNumber = getNumber(character);
System.out.print (finalNumber);
currentChar++;
}
System.out.print ("\n\nContinue? <y/n> ");
end = scan.next();
System.out.flush();
scan.nextLine();
currentChar = 0;
} while (!end.equalsIgnoreCase("n"));
}
public static int getNumber (char uppercaseLetter)
{
int resultChar = 0;
if (Character.isLetter(uppercaseLetter))
{
if (uppercaseLetter == 'A' || uppercaseLetter == 'B' || uppercaseLetter == 'C')
resultChar = 2;
else if (uppercaseLetter == 'D' || uppercaseLetter == 'E' || uppercaseLetter == 'F')
resultChar = 3;
else if (uppercaseLetter == 'G' || uppercaseLetter == 'H' || uppercaseLetter == 'I')
resultChar = 4;
else if (uppercaseLetter == 'J' || uppercaseLetter == 'K' || uppercaseLetter == 'L')
resultChar = 5;
else if (uppercaseLetter == 'M' || uppercaseLetter == 'N' || uppercaseLetter == 'O')
resultChar = 6;
else if (uppercaseLetter == 'P' || uppercaseLetter == 'Q' || uppercaseLetter == 'R' || uppercaseLetter == 'S')
resultChar = 7;
else if (uppercaseLetter == 'T' || uppercaseLetter == 'U' || uppercaseLetter == 'V')
resultChar = 8;
else if (uppercaseLetter == 'W' || uppercaseLetter == 'X' || uppercaseLetter == 'Y' || uppercaseLetter == 'Z')
resultChar = 9;
}
else if (Character.isDigit(uppercaseLetter))
{
resultChar = Character.getNumericValue(uppercaseLetter);
}
return resultChar;
}
}
我遇到的问题是,除了字母之外,我需要完全按用户输入的方式打印出电话号码。如果用户输入1-800-flowers,则程序需要将其打印为1-800-3569377。任何特殊字符都是相同的 - 连字符,空格,括号等。 而且解决方案越简单越好,因为我还没有得到数组或任何比方法更复杂的东西。