Just started doing it today and I ran into my first problem. I wrote the code but it has an error and I can't tell what it is. So if you could help me out that would be appreciated. Sorry if its super obvious.
Jeanne Boyarsky
,
author & internet detective
staff
Colton,
Welcome to CodeRanch! I've edited your post to add code tags and make it look all pretty .
This line is suspect. Since x doesn't change, it would make for an infinite loop. You don't say what "has an error" means. What should we be looking for? Did you get a compiler error? Did it not print out what you expected?
I got it by adding x = x + 1. But now when I run it it just keeps putting out big X over and over and doesn't stop.
public class Variables {
public static void main (String[] args) {
int x = 5;
while (x > 3) {
x = x + 1
if (x < 10) {
System.out.println("Small x");
} else {
System.out.println("Big X");
} // end else
} // end while loop
} // end main method
} // end class
So, tell me, when do you think the loop will end? (Actually, it will end eventually, but probably not when or why you expect it to.)
And in the future, please PostRealCode(⇐click) and UseCodeTags.(⇐click) You'll get better help if you show your actual code, and if you make it easy for people to read it.
when I run the program from the command prompt the words Big X continuously pop up like this
Big X
Big X
Big X
Big X
Big X
Big X
and on and on.
I need help with how to make it only pop up once.
Colton Herren wrote:when I run the program from the command prompt the words Big X continuously pop up like this
Big X
Big X
Big X
Big X
Big X
Big X
and on and on.
I need help with how to make it only pop up once.
If you want it to run only once, why are you using a loop? I loop is for when you want to do something multiple times (or potentially multiple times).
So, under what conditions (in English) do you want the loop to stop or to keep going? Or do you really want it to just go exactly once no matter what?
Glad it’s sorted, but it didn’t print Big X for ever after you put the increment in the loo. It printed Big X maybe 2147483637 times. If you had counted it, you would have seen.
It kept printing so long you thought it would never stop, but it would in fact have stopped eventually. After the addition of x = x + 1;, that is. Find out about x++; as shorthand for that line.
[edit]I see Jeff has already introduced you to x++[/edit]
Post by:autobot
It would give a normal human mental abilities to rival mine. To think it is just a tiny ad:
a bit of art, as a gift, that will fit in a stocking