*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes For loop / variable ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "For loop / variable ?" Watch "For loop / variable ?" New topic
Author

For loop / variable ?

Willie Toma
Ranch Hand

Joined: May 11, 2001
Posts: 78
Why does the following code print only "Total 0"?
public class Calc {
public static void main (String args []) {
int total = 0;
for (int i = 0, j = 10; total > 30; ++i, --j) {
System.out.println(" i = " + i + " : j = " + j);
total += (i + j);
}
System.out.println("Total " + total);
}
}
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
Willie
In your for loop the condition is set to be total > 30, meaning that as long as total is greater than 30 it will run. Since total starts out as 0 it is never greater than 30 so your loop never executes and so total stays at 0. If you make it 'total < 30' then it will run until total is greater than 30 and you'll get something other than 0.

hope that helps
Dave


Dave
Willie Toma
Ranch Hand

Joined: May 11, 2001
Posts: 78
Thanks!
 
jQuery in Action, 2nd edition
 
subject: For loop / variable ?