Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

while() trouble

 
Rajesh Chandra
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 657
Clojure Spring VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic