我正在尝试编写经典的初学者代码,然后在其中生成一个随机数,然后要求用户尝试猜测。我也尝试通过使用JOptionPane获得一些幻想。除了对用户猜测随机数的次数进行计数的变量以外,其他所有方法都工作正常。它总是只比应有的值小一个值(如果我第三次尝试正确,它说我一分为二)。我该如何解决?

第二个问题-我有out.println(randomNum);在我要求用户猜测这个数字之前(我可以作弊),但是直到我猜了一次之后,它才在控制台中显示。那是怎么回事?任何帮助将不胜感激!

int randomNum = new Random().nextInt(11); //define random number
    int guess = Integer.parseInt(JOptionPane.showInputDialog("Guess a number from 1-10: "));
    int numGuesses = 1;
    out.println(randomNum); //cheater
    guess = Integer.parseInt(JOptionPane.showInputDialog("Guess a number from 1-10: "));
    while (guess != randomNum) {
        ++numGuesses; //to increase the value of numGuesses by 1 each time the while loop iterates

        guess = Integer.parseInt(JOptionPane.showInputDialog("Guess a number from 1-10: "));

     }
    JOptionPane.showMessageDialog(null, "You got it right after only " + numGuesses + " tries!");
    out.println(numGuesses); //To see if it matches the JOptionPane value

最佳答案

1)您要求用户在进入while循环之前猜测两次该数字。由于numGuesses设置为1并在进入while循环时加1,所以您将被除一(您要让用户在while循环中第三次猜测数字)。

2)由于您是在提示用户猜测数字之后才打印“作弊者”代码,因此该数字只会在猜测之后出现。

请注意,Random().nextInt(11)也包括0,因此您可能希望将guess初始化为-1,如下例所示:

    int randomNum = new Random().nextInt(11); //Define random number between 0 (inclusive) and 10 (inclusive)
    int guess = -1;
    int numGuesses = 0;

    out.println(randomNum); //Cheater

    while (guess != randomNum) {
        guess = Integer.parseInt(JOptionPane.showInputDialog("Guess a number from 0-10: "));
        numGuesses++; //To increase the value of numGuesses by 1 each time the while loop iterates
     }

    JOptionPane.showMessageDialog(null, "You got it right after only " + numGuesses + " tries!");
    out.println(numGuesses); //To see if it matches the JOptionPane value

关于java - 隐藏在某处的愚蠢初学者错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26415993/

10-09 09:10