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

how to end a while loop in python
while loops python
python while loop multiple conditions
conditional loop python
while loop example
for loop
for loop python
while loop matlab

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 . 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. 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. 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
}

Loops: while and for, For example, outputting goods from a list one after another or just running the same code The loop will first execute the body, then check the condition, and, while it's truthy, To make an “infinite” loop, usually the while(true) construct is used. For each loop write down which values it is going to show. The while first tests nLoopCount. If nLoopCount is greater than 0, the program enters the body of the loop (the body is the code between the braces), where it decrements nLoopCount by 1 and outputs the result to the display. The program then returns to the top of the loop to test whether nLoopCount is still positive.

You return from the method after the first character was handled. 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. Now, let's process a 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. parseString parses the String in the way your code suggested. 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.

Python "while" Loops (Indefinite Iteration) – Real Python, Execution returns to the top of the loop, the condition is re-evaluated, and it is still true. The loop resumes, terminating when n becomes 0 , as previously. Remove  keep doing something until a condition is true; or. keep doing something while a condition is true. These are the most dangerous types of loop, since it's so easy for the condition never to happen! In this case you'll be looking at an hourglass while your computer's CPU gradually starts warming up with the effort it's putting in

As an alternative you could use String.relaceAll instead of checking each char in a nested 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;
}

4. Conditionals and loops, The boolean expression after the if statement is called the condition. If it is true, then all the indented statements get executed. Here, the first print statement will execute if food is equal to 'spam' , and the print statement satisfied. indefinite iteration: A loop where we just need to keep going until some condition is met. After the first run-through of the loop body, the loop condition is going to be evaluated for the second time. 1 < 10 still evaluates to true and the next iteration can commence.

I would suggest you to use StringBuilder as compared to String as it is preferable performance wise compared to String. The reason is String is immutable. So inside the loop the String object will be created again and again. Whereas StringBuilder is mutable so it is declared only once and then can be operated on by it's reference. 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. Pay attention to switch from concatination(+) to Builder.

while loop to repeat when condition is true, To mimic the behavior of a dowhile loop, set the initial condition of while to true and place the conditional expression inside the loop. For example, implement  end. If the condition is met, the code will break out of the while loop. If the condition is not met, the code will automatically loop back to the beginning of the while loop. Note: This loop construct is typically known as a DO-UNTIL loop.

in a nested for loop, if statement: how to keep doing something until , How would I write it so that if the first randomly selected entry is not present, I go back to for ii=1:6 for jj=1:6 % going over each entry in the matrix I'd need to write something after else, but I'm not sure how I'd do this. and the test will go on until ISMEMBER return true, because in this case the BREAK breaks the loop. Computer Science. Data Structures. The following pseudocode is an example of ____. if conditionC is true then. while conditionF is true. Click card to see definition 👆 Tap card to see definition 👆 A) single alternative structures. Click again to see term 👆 Tap again to see term 👆 In older languages, you could leave a selection or

How to Use If-Else Statements and Loops in R – Dataquest, Control structures set a condition and tell R what to do when that condition is met or not met. If statements tell R to run a line of code if a condition returns TRUE . Keep in mind that we'll have to use [[]] when indexing, since we want to return a Once the loop displays the result from the first iteration, the loop will look at  An infinite loop occurs when the loop-continuation condition in a DoWhileLoop or DoLoopWhile statement. never becomes false. The DoLoop Until statement checks the loop-termination condition_________. for True after the loop body executes.

Head First PHP & MySQL, So when the mysqli_fetch_array() function returns a row of data, the $row array is And since the test condition is true, the loop keeps on chugging. What's And this causes the while loop to never make it into the action code, not even once. The expression in the while statement header on line 2 is n > 0, which is true, so the loop body executes. Inside the loop body on line 3, n is decremented by 1 to 4, and then printed. When the body of the loop has finished, program execution returns to the top of the loop at line 2, and the expression is evaluated again.

Comments
  • The loop is stopping because return terminates the loop. You probably want to store the numbers somewhere and then return that rather than return individual numbers in a loop (which doesn't make sense because it will always terminate on the first iteration)
  • It sounds like you want to append the characters to a string and return the string after the loop, rather than return a single character.
  • you're welcome! feel free to mark it as the answer in order to close the question. Good luck with the rest of your coding!