0

I want my program to keep asking the question until it gets a response it can use, specifically a number from 0 to 20. I have a lot of other stuff on this class, so here is a small excerpt where the do-while is (I have named the variables and all that for everything).

public static void main(String[] args) {
    do {
        halp = 1;
        System.out.println("What level is your fort?");
        Scanner sc = new Scanner(System.in);

        try { 
            fortLevel = Integer.parseInt(sc.nextLine()); 
        }
        catch(NumberFormatException e){System.out.println("Numbers only, 0-20"); halp = 0;
    }

    if(halp < 1) {
        work = false;
    }

    if(halp > 1) {
        work = true;
    }

    while(work = false);
}
1
  • is there any reason to create the scanner inside of the loop? Commented Dec 26, 2012 at 18:51

3 Answers 3

4
while(work = false); // here you are assigning false to work

should be

while(work == false); //here you are checking if work is equal to false
  • = an assignment operator used to assign value
  • == an equality operator used to check if two operands have same value.

As work is boolean you could even just use this:

while(!work)
Sign up to request clarification or add additional context in comments.

Comments

3

You are using an assignment in your while expression:

while(work = false);

You can replace with

while(work == false);

or better

while(!work);

If variables halp and work are not used anywhere else, they could be eliminated giving you:

do {
   System.out.println("What level is your fort?");
   Scanner sc = new Scanner(System.in);
   try {
    fortLevel = Integer.parseInt(sc.nextLine());
   } catch (NumberFormatException e) {
     System.out.println("Numbers only, 0-20");
   }

} while (fortLevel < 0 || fortLevel > 20);

2 Comments

i've done this, but it still types out the "numbers only, 0-20" and then doesn't allow me to retype sc
You are setting halp to 1 which makes work true so you exit the loop immediately.
0

You could also do this:

if(!work) {break;}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.