首页 > 解决方案 > 第一个条件返回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 "";



}
}

标签: javaloops

解决方案


您希望将字符串结果附加到一个字符串,该字符串将在您遍历给定电话号码时继续增长。

在循环之前创建一个字符串变量,然后简单地附加到该字符串而不是返回字符串。然后,一旦您完成了电话号码的迭代,您就可以返回字符串。

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
}

推荐阅读