java - 第一个条件返回true后如何使循环继续进行
问题描述
我正在尝试编写一个方法,该方法将采用字符串,将任何字母转换为 int,并将所有转换后的 int 返回到 main,替换 letters 。我有将所有字母转换为数字的 if 语句,但我无法使用循环来转换所有字母,而不是在第一个字母之后停止。任何帮助将不胜感激,在此先感谢。
public class PhoneNumberChecker
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
// Get the phone number
System.out.print("Phone number to convert: ");
String phoneNumber = input.nextLine();
// Process each character in the phone number for display
for (int i = 0; i < phoneNumber.length(); ++i)
{
// Get the character
char ch = phoneNumber.charAt(i);
if (Character.isLetter(ch))
ch = (Character.toUpperCase(ch));
else
System.out.print(ch);
}
System.out.println(getNumber(phoneNumber));
input.close();
// end method
}
public static String getNumber(String phoneNumber)
{
for (int i = 0; i < phoneNumber.length(); ++i)
{
char ch = phoneNumber.charAt(i);
ch = Character.toUpperCase(ch);
if (ch == 'A' || ch == 'B' || ch == 'C')
return "2";
else if
(ch == 'D' || ch == 'E' || ch == 'F')
return "3";
else if
(ch == 'G' || ch == 'H' || ch == 'I')
return "4";
else if
(ch == 'J' || ch == 'K' || ch == 'L')
return "5";
else if
(ch == 'M' || ch == 'N' || ch == 'O')
return "6";
else if
(ch == 'P' || ch == 'Q' || ch == 'R' || ch == 'S')
return "7";
else if
(ch == 'T' || ch == 'U' || ch == 'V')
return "8";
else if
(ch == 'W' || ch == 'X' || ch == 'Y' || ch == 'Z')
return "9";
}
return "";
}
}
解决方案
您希望将字符串结果附加到一个字符串,该字符串将在您遍历给定电话号码时继续增长。
在循环之前创建一个字符串变量,然后简单地附加到该字符串而不是返回字符串。然后,一旦您完成了电话号码的迭代,您就可以返回字符串。
public static String getNumber(String phoneNumber){
String convertedNum = "";
for (int i = 0; i < phoneNumber.length(); ++i)
char ch = phoneNumber.charAt(i);
ch = Character.toUpperCase(ch);
if (ch == 'A' || ch == 'B' || ch == 'C')
convertedNum = convertedNum + "2"; //append to the string
else if(ch == 'D' || ch == 'E' || ch == 'F')
convertedNum = convertedNum + "3";
...
return convertedNum; //then return it at the end
}
推荐阅读
- r - 如何对 R 中的 MICE 估算数据执行混合设计方差分析?
- python - 在 Django admin 中显示内联子项
- php - 呈现错误的表单后如何重定向到页面上的位置
- c++ - 将外部库中的定义隐藏到我的代码中
- xml - 如何将元素插入子节点
- mongodb - mongodb 模型在调用函数 levelQuestion 时包含更改
- loops - SSIS foreach 循环枚举器 empty 为空 - 仅在部署时
- makefile - *.c 在依赖 xh 更改时不会反抗,使用自动生成的 *.d 文件
- tfs - Azure Devops - 是否可以防止复制或克隆工作项
- node.js - TypeError [ERR_UNESCAPED_CHARACTERS] 请求路径包含非转义字符