0

该程序的目标是让它接受一个电话号码,如 1-800Flower,并将其更改为相当于电话键盘的号码,如 1-8003569377 我似乎无法正确地将字母转换为数字。

import java.util.Scanner;  
public class Phonekeypad 
{
  public static int getNumber (char uppercaseLetter)
  {  
     int k = 0;
     switch (uppercaseLetter) 
     {
        case 65: k = 2;
        break;
        case 66: k = 2;
        break;
        case 67: k = 2;
        break;
        case 68: k = 3;
        break;
        case 69: k = 3;
        break;
        case 70: k = 3;
        break;
        case 71: k = 4;
        break;
        case 72: k = 4;
        break;
        case 73: k = 4;
        break;
        case 74: k = 5;
        break;
        case 75: k = 5;
        break;
        case 76: k = 5;
        break;
        case 77: k = 6;
        break;
        case 78: k = 6;
        break;
        case 79: k = 6;
        break;
        case 80: k = 7;
        break;
        case 81: k = 7;
        break;
        case 82: k = 7;
        break;
        case 83: k = 7;
        break;
        case 84: k = 8;
        break;
        case 85: k = 8;
        break;
        case 86: k = 8;
        break;
        case 87: k = 9;
        break;
        case 88: k = 9;
        break;
        case 89: k = 9;
        break;
        case 90: k = 9;
        break;        
    }
     return k;
  }


public static void main(String[] args) 
{ 
     String s;
     System.out.println("Enter a string: ");
     Scanner input = new Scanner(System.in);
     s = input.next().toUpperCase();
     for (int i=0; i<s.length(); i++)
     {
         char c = s.charAt(i);
        // Is this a letter?
         if (Character.isLetter(c))
         { 
            int n;
            n = getNumber(c);
            char cn = 0;
            switch (n)
            {
             case 2: cn = '2';
             break;
             case 3: cn = '3';
             break;
             case 4: cn = '4';
             break;
             case 5: cn = '5';
             break;
             case 6: cn = '6';
             break;
             case 7: cn = '7';
             break;
             case 8: cn = '8';
             break;
             case 9: cn = '9';
             break;
            }
            s.replace(c, cn);
         }
     }
         System.out.println(s);
    }
}
4

2 回答 2

2

你需要改变

   s.replace(c, cn);

 s = s.replace(c, cn);

否则字符串s将不会被更新。这背后的原因是在Java 中所有字符串都是不可变的(即它们不能改变)。每当您“更改”一个字符串时,您真正要做的就是创建两个字符串并交换它们的引用。replace() 知道这一点。这就是为什么不修改作为参数传递的字符串的原因。相反,replace() 返回一个新字符串,该字符串表示已替换字符的字符串“s”。

于 2012-11-29T22:16:02.490 回答
0

查看dreamcrash 的解决方案。无关,您可以通过组合案例语句来简化一些代码。例如,而不是

case 65: k = 2;
break;
case 66: k = 2;
break;
case 67: k = 2;
break;

你可以有

case 65:
case 66:
case 67: k = 2;
break;
于 2012-11-29T22:20:41.207 回答