简体   繁体   English

在第一个条件返回true后,如何使循环继续进行

[英]How can I make a loop keep going after the first condition returns true

I am trying to write a method that will take a string, convert any letters to an int, and return all the converted ints to main, replacing the letters . 我正在尝试编写一种方法,该方法将使用字符串,将任何字母转换为int,并将所有转换后的int返回main,以替换字母。 I have if statements that convert all the letters to numbers, but I am having trouble making it work with a loop to convert all the letters instead of stopping after the first one. 我有if语句,可以将所有字母转换为数字,但是我很难使它与循环转换所有字母而不是在第一个字母之后停止循环一起工作。 Any help would be appreciated, thanks in advance. 任何帮助将不胜感激,在此先感谢。

    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 "";



}
}

You want to append the string results to a string that will continue to grow as you iterate over the given phone number. 您想将字符串结果附加到一个字符串上,该字符串将在迭代给定电话号码时继续增长。

Create a String variable before your loop, then simply append to that string instead of returning the strings. 在循环之前创建一个String变量,然后简单地追加到该字符串而不是返回字符串。 Then once you're done iterating the phone number you can return the String. 然后,一旦完成电话号码的迭代,就可以返回字符串。

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
}

You return from the method after the first character was handled. 处理完第一个字符后,您将从方法中return Let's modify your method: 让我们修改您的方法:

public static String getNumber(String phoneNumber, int i)
{

    //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 "";
}

Note, that it has an int parameter and the cycle was commented out. 注意,它具有一个int参数,并且该循环已被注释掉。 Now, let's process a String : 现在,让我们处理一个String

public static function parseString(String input) {
    String output = "";
    for (int i = 0; i < input.length; i++) {
        output += getNumber(input, i);
    }
    return output;
}

Note, that this is very simple to understand. 注意,这很容易理解。 The thing which makes it simple is the fact that a method is doing a single thing. 使事情变得简单的事实是方法正在做一件事情。 getNumber gets a number from a String at a given index. getNumber从给定索引的String获取一个数字。 parseString parses the String in the way your code suggested. parseString以您的代码建议的方式解析String Of course you can modify the initial String if that is the purpose, using setChar , but then the getNumber method should return the char representation of the digits. 当然,如果setChar ,可以使用setChar修改初始String ,但是getNumber方法应该返回数字的char表示形式。

As an alternative you could use String.relaceAll instead of checking each char in a nested if-else. 或者,您可以使用String.relaceAll而不是检查嵌套的if-else中的每个字符。 Example: 例:

public static String getNumber(String phoneNumber){
    String result = phoneNumber.toUpperCase()
            .replaceAll("[A-C]", "2")
            .replaceAll("[D-F]", "3")
            .replaceAll("[G-I]", "4")
            .replaceAll("[J-L]", "5")
            .replaceAll("[M-O]", "6")
            .replaceAll("[P-S]", "7")
            .replaceAll("[T-V]", "8")
            .replaceAll("[X-Z]", "9");
    return result;
}

I would suggest you to use StringBuilder as compared to String as it is preferable performance wise compared to String. 我建议您将StringBuilderString相比,因为与String相比,它在性能方面更可取。 The reason is String is immutable . 原因是String是immutable So inside the loop the String object will be created again and again. 因此,在循环内将一次又一次创建String对象。 Whereas StringBuilder is mutable so it is declared only once and then can be operated on by it's reference. StringBuilder是可变的,因此只能声明一次,然后可以通过其引用对其进行操作。 You can use it as shown below: 您可以如下所示使用它:

public static String getNumber(String phoneNumber){

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < phoneNumber.length(); ++i){
        char ch = phoneNumber.charAt(i);
        ch = Character.toUpperCase(ch);

        if (ch == 'A' || ch == 'B' || ch == 'C')
            sb.append("2"); 
        else if(ch == 'D' || ch == 'E' || ch == 'F')
            sb.append("2");

        else if(ch == 'G' || ch == 'H' || ch == 'I')
            sb.append("3");
        else if(ch == 'J' || ch == 'K' || ch == 'L')
            sb.append("4");
        else if(ch == 'M' || ch == 'N' || ch == 'O')
            sb.append("5");
     }

     return sb.toString(); 
}

You can read about performance of String vs StringBuilder here . 您可以在此处阅读有关String vs StringBuilder的性能。 Pay attention to switch from concatination(+) to Builder . Pay attention to switch from concatination(+) to Builder

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM