gpt4 book ai didi

java - 需要帮助修复我的 Java 代码,将字母电话号码转换为完整的数字等效项

转载 作者:行者123 更新时间:2023-12-02 07:25:28 24 4
gpt4 key购买 nike

该程序的目标是让它接受像 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);
}
}

最佳答案

你需要改变

   s.replace(c, cn);

 s = s.replace(c, cn);

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

关于java - 需要帮助修复我的 Java 代码,将字母电话号码转换为完整的数字等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13635658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com