I am writing a code that will decode a 10 digit phone number that contains letters into all numbers. i.e 1-800-iloveny would get converted into 1-800-4568369. So far I've only encountered one problem, but have two questions. Do my if() statements correctly convert the current char in the string to an int? Then the main problem I have is that my code won't add the converted chars into the new string that will then output the decoded phone number (Assuming I converted them correctly).

class PhoneNumber
{
String phoneNumber;

public PhoneNumber(String num)
{
    phoneNumber = num;
}

public String decodePhoneNumber()
{
    phoneNumber = phoneNumber.toLowerCase();
    String decodedNumber = "";

    for(int cnt = 0; cnt < phoneNumber.length();cnt++)
    {
       char ch = phoneNumber.charAt(cnt);
       if((ch=='a')||(ch=='b')||(ch=='c'))
       {
           ch = 2;
       }
       else if((ch=='d')||(ch=='e')||(ch=='f'))
       {
           ch = 3;
       }
       else if((ch=='g')||(ch=='h')||(ch=='i'))
       {
           ch = 4;
       }
       else if((ch=='j')||(ch=='k')||(ch=='l'))
       {
           ch = 5;
       }
       else if((ch=='m')||(ch=='n')||(ch=='o'))
       {
           ch = 6;
       }
       else if((ch=='p')||(ch=='q')||(ch=='r')||(ch=='s'))
       {
           ch = 7;
       }
       else if((ch=='t')||(ch=='u')||(ch=='v'))
       {
           ch = 8;
       }
       else if((ch=='w')||(ch=='x')||(ch=='y')||(ch=='z'))
       {
           ch = 9;
       }

       decodedNumber = decodedNumber + ch;
    }
    return decodedNumber;
}
}

and then a sample inputted string would look as follows:

public class TestPhoneNumber
{
public static void main(String[] args)
{
    PhoneNumber ph1 = new PhoneNumber("1-800-ILOVENY");
    System.out.println("Decoded phone number: " + ph1.decodePhoneNumber());
}
}

However the final output turns out to look like: Decoded phone number: 1-800-

有帮助吗?

解决方案

int and char are different. You should use '2' in place of 2, etc.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top