hi
while(true)
{
i need a partcular section of code runs only once
}
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
hi
while(true)
{
i need a partcular section of code runs only once
}
Remove the while(true) { and ending } and the code will only execute once.
Do you know about the break statement?
As Norm mentioned, there is not need for a while if you only need the code to execute once. If you need the code to execute at least once, the use do{} while()
I need to use while loop as its the threads run method ,
but in that loop i want a section of code to ecxecute once , or for a particular count..
public Run()
{
while(true)
{
[ this section of code runs for 200 counts]
[this scode runs only once]
}
Last edited by jack_nutt; June 18th, 2011 at 08:04 PM.
If the section of code is inside the while loop, then use a boolean oneTime switch in an if statement
Define the boolean variable as true outside the loop. The inside the loop:
if (oneTime) { oneTime = false; // flip the switch to prevent execution next loop around // do the one time stuff } // end if
jack_nutt (June 18th, 2011)
I don't see why it has to be inside the while loop - surely only the code that needs to run many times should be in the loop. One-time code should be before or after the loop, as appropriate.
Also, if you need code executed 200 times, why not use a 'for..' loop that counts 200 iterations? A 'while(true)' loop is really only suitable for loops with an indefinite number of repeats (and not particularly good practice).