This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Help with while Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Help with while" Watch "Help with while" New topic
Author

Help with while

sumaraghavi ragha
Ranch Hand

Joined: Nov 17, 2006
Posts: 118
class NoBody
{
public static void main(String[] args)
{
int i,j;
i=100;
j=200;
while(++i ==102)
System.out.println("Mid point is" + i);
}
}
Why their is no output?
damodar kumar
Ranch Hand

Joined: May 19, 2008
Posts: 77

because at first i value is 100, in expression ++i its preincrementing i to 101 and checking with 102 whether it is equal or not , it is not equal so it comes put of loop ans again the i value is 100 only , so it wont print any output


<a href="http://stackoverflow.com/users/668970/user668970" rel="nofollow">
<img src="http://stackoverflow.com/users/flair/668970.png" >
</a>
Mark Vedder
Ranch Hand

Joined: Dec 17, 2003
Posts: 624

Originally posted by damodar kumar:
because at first i value is 100, in expression ++i its preincrementing i to 101 and checking with 102 whether it is equal or not , it is not equal so it comes put of loop ans again the i value is 100 only , so it wont print any output


Actually, when it comes out of the "loop", its value is still 101 since nothing else changes i's value or decrements it.
Mark Vedder
Ranch Hand

Joined: Dec 17, 2003
Posts: 624

sumaraghavi,

You are probably looking to do something more along the lines of this:



but that would be an unusually construct. Generally, when using a counter or index, like i, a 'for' loop is used rather than a 'while' loop. While both a 'while' loop and a 'for' loop would be syntactically correct, the 'for' loop is more conventional, and easier to understand. So it will make your code easier for others to read and understand.



if you need i to be in scope after the 'for' loop, you can do this:


[ June 02, 2008: Message edited by: Mark Vedder ]
sumaraghavi ragha
Ranch Hand

Joined: Nov 17, 2006
Posts: 118
Thanks all
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Help with while
 
Similar Threads
zigzag traverse a matrix
Copying a sheet from an excel file to another excel file using Apache POI
how is the flow
Help with Character count from a file.
Position of Numbers?