• Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Java Do-while loop

ByBoz

New Coder
I'm trying to make a do-while loop that print out a + each time it runs. It works well but I need to solve how to make a condition to make in not to print a + if it runs 0 times. I get that do-while loops runs at least time but I need to make a condition. Example runLoop 4 = 4 and runLoop 7 = 7 but runLoop 0 = 1 meanwhile I dont want it to get any +
Java:
public static void runLoop(int x){
        
    int runLoop = 1;
    
    // Here I need a working if condition
    do
    {
    System.out.print("+");
    runLoop++;
    }
    while (runLoop <= x);
    
}
 
I'm trying to make a do-while loop that print out a + each time it runs. It works well but I need to solve how to make a condition to make in not to print a + if it runs 0 times. I get that do-while loops runs at least time but I need to make a condition. Example runLoop 4 = 4 and runLoop 7 = 7 but runLoop 0 = 1 meanwhile I dont want it to get any +
Java:
public static void runLoop(int x){
       
    int runLoop = 1;
   
    // Here I need a working if condition
    do
    {
    System.out.print("+");
    runLoop++;
    }
    while (runLoop <= x);
   
}
Hi there,

What you can do is check inside the do block for x > 0, and put what you need run inside of that if statement
 
That's what you get for choosing a do.. while loop ! This always goes into the loop once, and only then evaluates the condition to see if it needs to continue. It can have its uses, but generally you are better off just using a simple while. Just put the while at the beginning where the do used to be:

Java:
public static void runLoop(int x){      
    int runLoop= 1;  
    while ( runLoop<= x )
    {
        System.out.print("+");
        runLoop++;
    }  
}

Adding an if to make the do..while work would be getting the wrong end of the stick.

BTW I'm surprised Java allows to you use a variable (runLoop) with the same name as the enclosing method. It actually works but IMHO it's bad programming practice.
 
Top Bottom