Back | Reverse | Quick Reply | Post Reply |

Java: looping
Link | by りんーちゃん on 2005-11-07 04:14:28
can you guys teach me looping? the one with the do{, while{....
I was on OB when my teacher taught my classmates that and now, I can't ask him to teach me since now, he's on OB in manila... Please don't just give me sites. >_<'


      
  m y . L i F E . i . t r a d e . i n . f o r . y o u r . P A i N .

Re: Java: looping
Link | by gendou on 2005-11-07 14:57:02
int i = 10;
while (i > 0)
{
system.out.println(i);
i = i - 1;
}
system.out.println("done");

the above code will print out "10 9 8 7 6 5 4 3 2 1 done!"
when i becomes zero, the loop exits

do loops check after the body, while loops check before


Re: Java: looping
Link | by RzmmDX on 2005-11-09 01:26:30
do{
System.out.print("Hi");
int i=0;
i++;
System.out.println(""+i);
}
while(i<5)

i think that's how a do-while loop should be...haven't done java for a long time and my JBuilder died

Ģöţ ñõţħįňģ Ţθ ĻÖŠĔ, ĕυεгұтђīŋġ ŧÅ? ĢĄİŇ, ₣řέёÄ?Å?м ằήđ Ĵůśťїçè, ČθгŗůÏ?ŧìÅ?Å‹ ằήđ Ä‹Å?ňƒīņěΜәπŧ, Vâļóůѓ ịή βαŧŧļé, Ħõńòґ ÏŠÅ„ Ä?Ä•Ä?ţħ

Re: Java: looping
Link | by Inggo on 2005-11-12 21:11:07
Actually, RzmmDX, that won't work. You have to put the conditional variable outside the loop. That would generate an infinite loop. It should be:

int i = 0;
do {
System.out.print("Hi");
i++;
System.out.println(""+i);
} while(i<5);

Would print out:
Hi1
Hi2
Hi3
Hi4
Hi5

And don't forget the semicolon when using do-while loops. The format of a do-while loop is:

do {
...
} while (condition);

Make sure the variable you use is outside and before the loop.

You can also do loops with while, like Gendou did. The main difference is that do-while loops guarantee the loop to perform the actions inside at least once before it checks the condition. The basic format is:

while(condition) {
...
}

Another loop type is a for loop:

for(int i = 0; i < 5; i++) {
System.out.print("Hi");
System.out.println(""+i);
}

This code basically does the same as the do-while loop above in a different format:

for(variable initializations, condition, increment) { ... }

Back | Reverse | Quick Reply | Post Reply |

Copyright 2000-2024 Gendou | Terms of Use | Page loaded in 0.0024 seconds at 2024-03-28 16:41:57