File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes while() trouble Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "while() trouble" Watch "while() trouble" New topic

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)
// if(i % 10==0) System.out.println(i);
}catch(Exception e){}
public static void main(String st[]){

As1 a=new As1();
Thread t=new Thread(a);

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.
I agree. Here's the link:
subject: while() trouble
It's not a secret anymore!