| Author |
while() trouble
|
Rajesh Chandra
Ranch Hand
Joined: Jun 13, 2005
Posts: 55
|
|
Please refer to the code below.Why does it print only 0?? Why doesnt it count from 0 to 99??However when i use if statement it works fine. public class As1 implements Runnable{ public void run(){ for(int i=0;i<100;i++){ while(i % 10==0) { System.out.println(i); } // if(i % 10==0) System.out.println(i); try{ Thread.sleep(1000); }catch(Exception e){} } } public static void main(String st[]){ As1 a=new As1(); Thread t=new Thread(a); t.start(); } } thanks in advance regs rajesh
|
 |
Steve Morrow
Ranch Hand
Joined: May 22, 2003
Posts: 657
|
|
The first time through your for loop, the value of i is 0. Within that first loop, you start a new loop that says while i % 10 == 0, print the value of i. Since 0 % 10 == 0, your while loop begins, prints i, then evaluates the condition again (i % 10 == 0). Since i is still 0, and 0 % 10 is still equal to 0, the while loop runs again, ad infinitum. Hope this helps.
|
 |
 |
|
|
subject: while() trouble
|
|
|