• Post Reply Bookmark Topic Watch Topic
  • New Topic

when the logical statement of while loop returns false , why that block is getting executed ?  RSS feed

 
naved momin
Ranch Hand
Posts: 692
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i know that do statement will execute no matter what , but when the logical statement of while loop returns false , why that block is getting executed
???



output is
the i is = 10
i is not 10 it is = 10


why while loop is getting executed when the i is not five ?
 
Greg Brannon
Bartender
Posts: 563
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The while loop is empty because there's a semi-colon at the end of the while statement.
 
naved momin
Ranch Hand
Posts: 692
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Greg Brannon wrote:The while loop is empty because there's a semi-colon at the end of the while statement.

but this is how we write do while loop
i got an error after removing " ;" semicolon.

 
fred rosenberger
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Lines 6-11 are a single construct called a "do-while" loop. This is a loop that will run 1 time no matter what, then exits when the 'while' condition is false.

After that loop is done, you have a block of code in lines 12-14 that have nothing to do with the loop, so they will always be executed.
 
Wouter Oet
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't see the problem. The do-while loop gets executed once. Then the statement after the while loop is executed. Maybe the extra unnecessary parenthesis confuse you.
 
Greg Brannon
Bartender
Posts: 563
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry. I focused on the while loop per the title and your question why the code after the while is executed and didn't see the 'do'.

I still think you meant the block of code after the while loop to somehow be affected by the while or do/while loops. You'll need another condition, like an if, to isolate the println statement to print only when i is not 10.
 
naved momin
Ranch Hand
Posts: 692
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Greg Brannon wrote:Sorry. I focused on the while loop per the title and your question why the code after the while is executed and didn't see the 'do'.

I still think you meant the block of code after the while loop to somehow be affected by the while or do/while loops. You'll need another condition, like an if, to isolate the println statement to print only when i is not 10.

thanks i got it
and even fix it !
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!