Click here to Skip to main content
15,881,715 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Should be a tiny problem that should easily be solved. My code works fine when x is assigned a value over 0, but when it is assigned 0 it either just prints "+" if i use while (x > 0); or if i use while (x != 0); it just infinite loops.

Any help would be very kind, thanks in advance!

What I have tried:

	public static void runLoop(int x){
		
		do {
			System.out.print("+");
			 x--;

		}
		while (x > 0); 

}

I also tried while (x != 0) but that seems to not work because x just skips 0 and it becomes an infinite loop when x is assigned the value 0.
public static void runLoop(int x){

    while(x !=0){
        System.out.print("+");
        x--;
    }
}

Looks like this when I did it in normal while-loop and it feels like i converted it right.
Posted
Updated 16-Jun-21 10:21am
v3

I tried it here with an online compiler and it does what I expected: pass it 0 and it prints one "+" character.

I suspect that either the code that calls that is the problem, or that isn;t the code you are executing.

And why do you have an empty curly bracket block after the while line? What do you expect that to do?
 
Share this answer
 
Comments
Rari0002 16-Jun-21 16:21pm    
Brackets are gone, don't know why they were there. I have tried switching around the "x--" but I can't seem to find the problem, it has worked fine with both a for loop and a normal while loop so I feel like it should work. They have different execution styles but don't know how that would affect this.
OriginalGriff 16-Jun-21 16:27pm    
As I said, it works fine when I test it - so you need to look at the surrounding environment rather than that code in isolation.
OriginalGriff 16-Jun-21 16:27pm    
What does the debugger show you is happening?
Rari0002 16-Jun-21 16:33pm    
Oh sorry might have phrased the question a bit all over the place. I do not want the program to print out any "+" when x is assigned the value 0, I want it to print out a blank space.
OriginalGriff 16-Jun-21 16:39pm    
Then you can't use a "do ... while" loop - the whole idea of those is that the test is executed after the loop body, not before: you always get at least one pass through the loop, even if the condition always evaluates to false.
Java
while (x !=0)
{
    System.out.print("+");
    if (x < 0)
        x++;
    else
        x--;
}
System.out.println(" ");
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900