程序不会退出循环,即使它认为它似乎知道

时间:2016-09-09 20:06:56

标签: java eclipse

我正在制作一个猜谜游戏,其中用户输入最高号码,而计算机选择1和用户输入的数字之间的数字。在猜到正确的数字之后,它应该离开do-while,然后移动到toString,但不是。

以下是一个例子:

Guessing Game - How many numbers? 10
Enter a number between 1 and 10: 1
Try again.

Enter a number between 1 and 10: 2
Try again.

Enter a number between 1 and 10: 3
Try again.

Enter a number between 1 and 10: 4
Enter a number between 1 and 10: 

你可以看到它没有说"再试一次,"但还是要求另一个猜测。

这是我的程序

import java.util.Scanner;
import static java.lang.System.*;

public class GuessingGame
{
    public int upperBound;
    int guesscount = 0;

    public GuessingGame(int stop)
    {
        upperBound = stop;
    }

    public int playGame()
    {
        boolean guesscorrectly = false;
        Scanner kb = new Scanner(System.in);
        int correctNum = (int) ((Math.random()*upperBound) +1);
        do{
            System.out.print("Enter a number between 1 and " + upperBound + ": ");
            int guess = kb.nextInt();
            if(guess==correctNum){
                guesscount++;
                guesscorrectly = true;
            }
            else{
                guesscount++;
                System.out.println("Try again.\n");
            }
        }while(guesscorrectly!=true);
        return correctNum;
    }

    public String toString()
    {
        return "You correctly guessed " + playGame() + "! It took you " + guesscount + " guesses.";
    }
}

然后这是主要的

import java.util.Scanner;
import static java.lang.System.*;

public class GuessRunner
{
    public static void main(String args[])
    {
        Scanner kb = new Scanner(System.in);
        System.out.print("Guessing Game - How many numbers? ");
        int upperBound = kb.nextInt();
        GuessingGame test = new GuessingGame(upperBound);
        test.playGame();
        System.out.println(test);
    }
}

2 个答案:

答案 0 :(得分:7)

您在playGame()方法中致电toString()。你不应该这样做,否则它将开始游戏......

答案 1 :(得分:0)

请注意,只要您在代码中执行playGame(),就会调用playGame()方法。这意味着该方法将在toString()内执行。你有三种方法来解决这个问题。

  1. 删除在test.playGame()中调用main()的行。然后将System.out.println()语句从toString()移至main(),将playGame()更改为test.playGame()

  2. 通过将playGame()赋值给变量来捕获它的返回值。然后,您可以在main()中打印该变量的值,而不是覆盖toString()

  3. 您可以创建一个存储该值的成员字段,而不是从playGame()返回值。然后toString()使用成员字段的值而不是调用playGame()