Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
i am just starting a java class and we are on do while loops i am having a bit of truble understanding how they work and how to use them. one of my questions is
"write a program that announces each times the loop has been run and type 'more' to continue and 'stop' to exit the program"
i dont whant the coding for it but how to understand do while loops and inputing info to exit it and such,
thanks in advanced

Boolean b = true;
While (b) {
Wait for user input
If more
Do nothing
If stop
b = false or System.exit(0)
}
Basically you need a checking variable.
While this condition is true do the loop.You can have anything like
Int num = 0
While (num != 10) {
num++
}

Kris's example is OK, but it doesn't really show why you would want to use a do-while loop instead of some other kind of loop.
Do while differs from the while loop only in that it always executes at least once. You have to execute at least once to get user input, then you decide whether or not you should keep going.
do
{
print "loop executed"
x=prompt("go again?")
} while x=='y'Compare this to a while loop that does the same thing:
x='y'
while(x=='y')
{
print "loop executed"
x=prompt("go again?")
}Or, if you wanted to get fancy, a for loop that does the same thing:
for (x='y'; x=='y'; x=prompt("go again?"))
print "loop executed"The for loop is the shortest, but a little less intuitive. The while loop is OK, but you have to give x the value of 'y' to get it started, or it will never work. The do-while is the best because it's short and easy to understand.
Avoid explicitly leaving loops and programs using breaks, exits, and System.exit when you can, as it makes your code difficult to follow.
On a side note, you did a good job explaining that you don't want code, just explanations. That is the best way to get answers for homework questions here.
Luck,
-SN

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |