Reputation: 21
I've tried several programs that involve printing to the console in for loops, but none of them have printed anything. I can't work out the problem, and I've boiled it down as simply as possible here:
for (int x=0; x==10; x++)
{
System.out.print("Test");
}
Like I said, absolutely nothing is printed to the console. Things outside of the for loop will print, and things affected by the for loop will print. Perhaps it's something very simple, but I wouldn't know considering I'm relatively new to programming and Eclipse gives me no errors. Any help would be much appreciated, as this is plaguing my class files at the moment.
Thanks,
Daniel
Upvotes: 0
Views: 142
Reputation: 188
rgettman is completely correct. A for
loop should be used as so:
for
is a type of loop in java that will take three parameters separated by semicolons ;
The first parameter will take a variable
such as int i = 0;
to create a simple integer
at 0.
The second parameter will take a condition such as i < 10
, to say while the i integer
is less than
The third and final parameter will take an incrementing value like, i++
, i--
, i +=5
, or something to that effect.
This part should like like for(int i = 0; i < 10; i++)
so far.
Now you need the brackets {
and }
. Inside of the brackets you will perform an action. Like you wanted to print "test" to the console.
for(int i = 0; i < 10; i++) {
System.out.println("test");
}
This would print "test" 10 times into the console. If you wanted to see what number i
was at, you could simply say,
for(int i = 0; i < 10; i++) {
System.out.println(i); // Current value of i
}
Hope this was of use to you!
Upvotes: 0
Reputation: 7764
@rgettman gave the reason your code didn't work above. The way the for loop works is in the brackets the first variable is where the loop starts (i.e. 'x=0'), the second variable is the condition (i.e. 'x<= 10'), and the third is what to do for each loop (i.e. 'x++').
You had "x==10" for the condition, so for the first scenario where x was equal to "0", the loop ended because it was NOT equal to "10". So you want it to be "x<=10" (x is less than or equal to 10); this will go through 11 loops.
Upvotes: 2
Reputation: 178333
Your for
loop condition is wrong. You want the condition to be true
to continue looping, and false
to stop.
Try
for (int x=0; x < 10; x++)
For more information, here's the Java tutorial on for
loops.
Upvotes: 6