首页 \ 问答 \ 获取新的随机数用于猜测Java中的游戏(Getting New Random Numbers For Guessing Game In Java)

获取新的随机数用于猜测Java中的游戏(Getting New Random Numbers For Guessing Game In Java)

我正在构建一个Java游戏,我已经完成了最后一个部分。 还有其他一些问题需要解决,这些问题很容易解决。 虽然有一个问题我无法弄清楚,也就是说每次运行游戏后我都无法获得新的随机数字。

例如,如果没有人猜测计算机从数字(1-20)随机生成的数字比游戏重复自己的数字。 在此期间你正在玩2台计算机,它们的数字也是随机组成的(再次是1-20个值)。

这是我制作的Player类的一些代码

import java.util.Scanner;
import java.util.Random;

public class Player {
    private double currentGuess = 0;
    private String firstName;
    private boolean isCorrect;
    Scanner myScanner = new Scanner(System.in);

public Player() {
}

public double autoGuess()   {
    Random randomNumber = new Random();
    double number = randomNumber.nextInt(20) + 1;

    return number;
}

这是我的GuessGame类,它是动作实际发生的地方。 我无法弄清楚为什么当我调用autoGuess方法(来自播放器类)时,我无法在每次游戏后显示新的随机数,导致没有人猜测正确的数字。 同样可以随机生成要猜测的数字(WINNING_NUMBER),每次新游戏后它仍然保持不变。 这是我的GuessGame类的一些代码。

import java.util.Random;

public class GuessGame {
    Player player1 = new Player();
    Player player2 = new Player();
    Player player3 = new Player();

    double player2Guess = player2.autoGuess();
    double player3Guess = player3.autoGuess();
    int numberOfTries = 0;

public double generateWinningNumber()   {
    Random randomGenerate = new Random();
    double randomNumber = randomGenerate.nextInt(20) + 1;

    return randomNumber;
}

private final double WINNING_NUMBER = generateWinningNumber();

public void startGame() {
    System.out.println("VM: Welcome we are going to play a number guessing game. I'm (the JVM)\n"
            + "going to randomly pick a number between 0 and 20. You and the 2 other\n"
            + "computer-generated players are going to try to guess that number. The game\n"
            + "will end when at least one of the players correctly guesses the number.\n");

    System.out.println(WINNING_NUMBER);

    System.out.print("What is your name?  ");
        String player1Name = player1.readName();

    while (player1.isCorrect() == false)    
        {

        System.out.print(player1Name + ", enter your guess:  ");
            player1.readGuess();
            player2.autoGuess();
            player3.autoGuess();

            numberOfTries++;

            if (player1.getCurrentGuess() == WINNING_NUMBER || player2Guess == WINNING_NUMBER || player3Guess == WINNING_NUMBER)
            {
                player1.setCorrect(true);
                displayGuesses();
                determineWinner();
            }

            else
            {
                displayGuesses();
                displayHints();
                System.out.println("No one guessed the number.\nPlayers will need to guess again.\n");
                System.out.println("The winning number was: " + WINNING_NUMBER);
                generateWinningNumber();
            }
        }   
}


public void displayGuesses()    {
    System.out.print("Player 2's guess is: " + player2Guess + "\n");
    System.out.print("Player 3's guess is: " + player3Guess + "\n\n");
}

还有更多内容,显然还有更多需要解决的问题,但我试图将此问题排除在外。 我有我的驱动程序类开始这个游戏,也知道我需要将我的数字舍入到Ints所以没有小数位。 此外,所有提示方法都指的是如果语句告诉您是否热,温或冷。 这完全没问题。 只需要一些帮助,找出如何在我的while语句中每次新的不成功游戏后获取一个新的随机数。


I am building a game for Java and I've gotten down to one of the last parts. There are still other things to fix which are easy fixes. Although there is one problem I can't figure out, which is that after every time I run the game I can't get new random numbers to show up.

For instance, if nobody guesses the number that is made at random by the computer from numbers (1-20) than the game repeats itself. You are playing 2 computers during this and their numbers are also made up at random (again 1-20 values).

Here is some of the code for the Player class I made

import java.util.Scanner;
import java.util.Random;

public class Player {
    private double currentGuess = 0;
    private String firstName;
    private boolean isCorrect;
    Scanner myScanner = new Scanner(System.in);

public Player() {
}

public double autoGuess()   {
    Random randomNumber = new Random();
    double number = randomNumber.nextInt(20) + 1;

    return number;
}

Here is my GuessGame class, which is where the action actually happens. I cannot figure out why when I call for the autoGuess method (from the player class) I cannot get new random numbers to show up after each game which resulted in nobody guessing the right number. Same goes for randomly generating the number to be guessed (WINNING_NUMBER), it still stays the same after every new game. Here is some of the code of my GuessGame class.

import java.util.Random;

public class GuessGame {
    Player player1 = new Player();
    Player player2 = new Player();
    Player player3 = new Player();

    double player2Guess = player2.autoGuess();
    double player3Guess = player3.autoGuess();
    int numberOfTries = 0;

public double generateWinningNumber()   {
    Random randomGenerate = new Random();
    double randomNumber = randomGenerate.nextInt(20) + 1;

    return randomNumber;
}

private final double WINNING_NUMBER = generateWinningNumber();

public void startGame() {
    System.out.println("VM: Welcome we are going to play a number guessing game. I'm (the JVM)\n"
            + "going to randomly pick a number between 0 and 20. You and the 2 other\n"
            + "computer-generated players are going to try to guess that number. The game\n"
            + "will end when at least one of the players correctly guesses the number.\n");

    System.out.println(WINNING_NUMBER);

    System.out.print("What is your name?  ");
        String player1Name = player1.readName();

    while (player1.isCorrect() == false)    
        {

        System.out.print(player1Name + ", enter your guess:  ");
            player1.readGuess();
            player2.autoGuess();
            player3.autoGuess();

            numberOfTries++;

            if (player1.getCurrentGuess() == WINNING_NUMBER || player2Guess == WINNING_NUMBER || player3Guess == WINNING_NUMBER)
            {
                player1.setCorrect(true);
                displayGuesses();
                determineWinner();
            }

            else
            {
                displayGuesses();
                displayHints();
                System.out.println("No one guessed the number.\nPlayers will need to guess again.\n");
                System.out.println("The winning number was: " + WINNING_NUMBER);
                generateWinningNumber();
            }
        }   
}


public void displayGuesses()    {
    System.out.print("Player 2's guess is: " + player2Guess + "\n");
    System.out.print("Player 3's guess is: " + player3Guess + "\n\n");
}

There is more to this and obviously more to fix, but I'm trying to just get this issue out of the way. I have my driver class starting this game and also know I need to round my numbers to Ints so there isn't a decimal place. Also, all the hint method is referring to is just if statements that tell you if you are hot, warm, or cold. That runs perfectly fine. Just needing some help with figuring out how to get a new random number after every new unsuccessful game from my while statement.


原文:https://stackoverflow.com/questions/26616897
更新时间:2023-06-14 15:06

最满意答案

您是否在创建项目时定位Google API? 尝试这个:

  1. 在Package Explorer中右键单击您的项目
  2. 单击“属性”。
  3. 点击“Android”标签
  4. 检查相应的“Google API”
  5. 应用更改并查看其是否有效。

Are you targeting the Google APIs when you create your project? Try this:

  1. Right-click your project in the Package Explorer
  2. Click on "Properties".
  3. Click on the "Android" tab
  4. Check the appropriate "Google API"
  5. Apply changes and see if it works.

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)