简体   繁体   中英

question on this java code segment

The following code is claimed to use a do loop with a flag to repeat input until a valid int is obtained.

 do
{      
  try
  {
    // attempt to convert the String to an int
    n = Integer.parseInt( s );
    goodInput = true;
  }
  catch ( NumberFormatException nfe )
  {
    s = JOptionPane.showInputDialog( null,
            s + " is not an integer. Enter an integer" );
  }
} while ( !goodInput );

I am a little confusing about the logic here. If the Integer.parseInt just works fine, or there is no exception occuring, then the "goodInput" is assigned to "true" at line of

 goodInput = true;

Then the,goodInput will be evaluated as False. so the while loop will continue again, This seems to me contradicts to the designed logic. ie,. the while loop should stop after performing a correct parse operation. What is wrong with my analysis above.

do { } while(x); loops while x == true , ie until x == false .

Therefore, do { } while(;x); loops while x == false , ie until x is true .

Then the,goodInput will be evaluated as False. so the while loop will continue again.

No - when the expression evaluates to false , then the loop stops.

Try to read it as normal English: "do (stuff) while (expression) is true".

A do/while loop behaves exactly like a normal while loop, except it is guaranteed to run at least once. It is best to think of it in those terms.

If it parses it correctly, goodInput is true, which makes,goodInput false. so the loop will end.

The do-while will stop looping when the condition (.goodInput in this case) evaluates to false. As long as it's true it will continue looping.

All analysis of yours are correct. Only when the while statement evaluation is false as you say, it won't loop again.

!goodInput must be false to terminate the loop. If goodInput is true, then !goodInput is false, so the loop terminates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM