while loop

i don't understand the output of this program at the start

why the two zero's? how do i change that?

class whileloop

{

publicstaticvoid main(String[] args)

{

int n = 0;int x = 0;

while (n !=10)

{

System.out.println(n);

n++;

while(x !=20)

{

System.out.println(x);

x++;

}

}

}

}

output

0 //the two zeros

0

1

2

3

4

etc

[954 byte] By [mark_8206a] at [2007-11-26 17:47:54]
# 1

Let us go through this with line by line.

> int n = 0; int x = 0;

n=0

x=0

> while (n !=10)

n!=10 == 0!=10 == true

> System.out.println(n);

n=0

so output "0"

> n++;

n=1

x=0

> while(x !=20)

x!=20 == 0!=20 == true

> System.out.println(x);

x=0

so output "0"

> x++;

n=1

x=1

> while(x !=20)

x!=20 == 1!=20 == true

etc...

mlka at 2007-7-9 5:00:13 > top of Java-index,Java Essentials,New To Java...
# 2
how do i get rid of the zeros?
mark_8206a at 2007-7-9 5:00:13 > top of Java-index,Java Essentials,New To Java...
# 3
> how do i get rid of the zeros?I think this is going nowhere.
warnerjaa at 2007-7-9 5:00:13 > top of Java-index,Java Essentials,New To Java...
# 4
> > how do i get rid of the zeros?> > I think this is going nowhere.So do I, but as I really don't want to work...mark, did you read my post above? Do you understand what it says?
mlka at 2007-7-9 5:00:14 > top of Java-index,Java Essentials,New To Java...
# 5
yeah i understand it
mark_8206a at 2007-7-9 5:00:14 > top of Java-index,Java Essentials,New To Java...
# 6
> yeah i understand itSo you understand why it prints zero twice? So it should be fairly obvious on how to stop it.
mlka at 2007-7-9 5:00:14 > top of Java-index,Java Essentials,New To Java...
# 7
i changed the x variable to 1 instead of 0 and now it worksi'm still a little confused but i'll get over it
mark_8206a at 2007-7-9 5:00:14 > top of Java-index,Java Essentials,New To Java...
# 8
> yeah i understand itSo, how did you get rid of the zeros?
prometheuzza at 2007-7-9 5:00:14 > top of Java-index,Java Essentials,New To Java...
# 9
one of them
mark_8206a at 2007-7-9 5:00:14 > top of Java-index,Java Essentials,New To Java...
# 10

> i changed the x variable to 1 instead of 0 and now it

> works

> i'm still a little confused but i'll get over it

What are you confused about. You have two loops, one within the other.

Maybe it would help if you change the System.outs to:

System.out.println( "n=" + n );

System.out.println( "x=" + x );

mlka at 2007-7-9 5:00:14 > top of Java-index,Java Essentials,New To Java...
# 11
> one of themYes.~
yawmarka at 2007-7-9 5:00:14 > top of Java-index,Java Essentials,New To Java...