简体   繁体   中英

Java help regarding looping (do loops)

I'm trying to make a very basic game where you guess a number between 1-1000 using a do loop. Everything works, except when I finally make the correct guess, I am still prompted to make another guess, and when I enter the same correct guess again, the program terminates like it's suppose to.

Why do I have to make that extra guess to finally get my program to work? Am I looping around an extra time? Also, if I make a correct guess (the compiler will say I am correct then still prompt me), then a wrong guess (the compiler will tell me I'm wrong), then the correct guess again, the program will only terminate after I make the correct guess a second time.

The second do loop at the bottom is what I put in my main method. Everything above is in a method I wrote called play.

public static boolean play()
{

    boolean c;
    int n = 0;

    do {
        String input = JOptionPane.showInputDialog("Enter a number between 1-1000");
        n = Integer.parseInt(input);

        if (n == guess)
        {
            System.out.println("Correct");
            c = true;
        }
        else if (n < guess)
        {
            System.out.println("Not Right");
            c = false;
        }
        else
        {
            System.out.println("Not Right");
            c = false;
        }

        guess++;

    } while (c == false);

    return c;

}

In main method:

    do {
        game1.play();
    } while (game1.play() != true);

This loop runs the play method twice in each iteration of the loop :

do {
    game1.play(); // first call
} while (game1.play()!=true); // second call

You are not testing the value returned by the first call, so even if it returns true, you would still call game1.play() again, which will display "Enter a number between 1-1000" again.

Replace it with:

boolean done = false;
do {
    done = game1.play();
} while (!done);

This would only call play() one time in each iteration of the loop.

That said, I'm not sure why you need the outer loop. You can just replace in with one call to game1.play() , since game1.play() will loop until the correct number is entered.

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