Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Simple java question: how do I convert this do-while loop to a while loop?

Here is my do while loop for a program I'm writing for an assignment (I already declared radius as an int, and a Scanner named 'input' was already set up):

do {

System.out.print("Enter the radius (use a number " +

"between 10 and 250): ");

radius = input.nextInt();

if (radius < 10 || radius > 250)

System.out.println("Not following directions.");

} while (radius < 10 || radius > 250);

What it is supposed to do is print out "Enter the radius (use a number between 10 and 250): "

and the user will input a number. If they put in an appropriate number, the progrm moves onto another do-while statement asking for more input. If they put in a number not between 10 and 250, it's supposed to spit out "Not following directions." and then restarts the beginning instructions until the user puts in an appropriate number.

I can't seem to translate this into a while loop properly. I make it infinite, and I see my error, I just can't figure out how to remedy it. I'm obviously a beginner, so an example would be very useful.

1 Answer

Relevance
  • 7 years ago
    Favorite Answer

    while() and do...while() loops have different semantics, which is why both a provided. You always want to do this at least once (to get the value first time) so do...while() is the natural style. You have to slightly obfuscate your code with a deliberately invalid initialization to convert to a straight while() loop:

    radius = 0;

    while (radius < 10 || radius > 250) {

    System.out.print("Enter the radius (use a number " +

    "between 10 and 250): ");

    radius = input.nextInt();

    if (radius < 10 || radius > 250)

    System.out.println("Not following directions.");

    }

Still have questions? Get your answers by asking now.