• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 944
  • Last Modified:

Do while loop syntax in java

I have some java code for a simple do while loop but it is exhibiting some strange behavior. Sometimes it works but sometimes it exits the loop when it is not supposed to. Can anyone see what I'm doing wrong with this?

I have checked that I am receiving keyboard input correctly and setting the flag to 4 when entered.
I have just put the relevant code.

Thank you
int flag = 0;
do
{
  if (flag == 4)
  {
  System.out.print("Quitting");						
  }
}
while(flag != 4);

Open in new window

0
GrimReeper
Asked:
GrimReeper
3 Solutions
 
Ajay-SinghCommented:
Its infinite loop for any value other than 4. What is that you want to achieve with this loop?
0
 
petr_hlucinCommented:
I suppose that value of flag is modified in a different thread. Make sure modyfying of this value takes place within a critical section.
0
 
GrimReeperAuthor Commented:
I want the loop to keep running until input is changed to 4 but the loop exits when input is 1.
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Monky42Commented:
You need to provide more information. If you are using multiple threads please post all code concerning the two threads and the synchronized flag value. If you are not using multiple threads you might have a design problem. The loop as you have posted it is senseless.
0
 
GrimReeperAuthor Commented:
I have changed it to a while loop and now it works. Strange but thanks for the help anyway.
0
 
GrimReeperAuthor Commented:
Thank you
0
 
GrimReeperAuthor Commented:
For anyone interested it ended up being the validation from another class I had was kicking in. I always forget the most simple of things that have the biggest consequences haha.
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now