简体   繁体   English

Java逆向猜测游戏

[英]Reverse Guessing Game for java

I've been trying to create a reverse guessing game wherein the user will input a number and then the program/bot will try to guess what number the user gave. 我一直在尝试创建一个反向猜谜游戏,其中用户将输入一个数字,然后程序/机器人将尝试猜测用户给出的数字。 I have a problem with random generator in the program. 我在程序中的随机数生成器有问题。 For example, when the user inputs a number such as 157, the bot will generate a number. 例如,当用户输入数字(例如157)时,机器人将生成一个数字。 If the number that bot gave is lower than 157, the user will then click the higher button (lower button if the number is higher). 如果bot给出的数字小于157,则用户将单击较高的按钮(如果数字较大,则单击较低的按钮)。 My problem is it doesn't generate properly and just give a random number. 我的问题是它不能正确生成,只能给出一个随机数。

I've tried changing the formula for Math.random() but I still can't figure it out. 我曾尝试更改Math.random()的公式,但仍然无法弄清楚。

Here's my code for the jbutton (higher) in netbeans : 这是我在netbeans中的jbutton(更高)的代码:

if(con > con2) {
    int generator = (int)(Math.random() * (1 + high - low))+low;
    String conv = Integer.toString(generator);
    jTextField2.setText(conv);
}

Your problem very likely does not lie in your random number generation. 您的问题很可能不在于您生成随机数。 When I run the following: 当我运行以下命令时:

int high = 20;
int low = 10;
for(int i = 0; i < 20; ++i)
{
    int generator = (int)(Math.random() * (1 + high - low))+low;
    System.out.print(generator+" ");
}

I get the following output: 我得到以下输出:

18 19 12 11 19 17 15 19 14 16 16 14 10 20 13 20 11 14 20 15 18 19 12 11 19 17 15 19 14 16 16 14 10 20 13 20 11 14 20 15

This generates random numbers between 10 and 20, inclusive. 这将生成10到20(含)之间的随机数。 So, if you're running into a problem with your random number generation, there are a few possibilities: 因此,如果您在生成随机数时遇到问题,则有以下几种可能性:

  • Your jTextField2.setText value is getting ignored 您的jTextField2.setText值被忽略
  • Your jTextField2.setText value is getting overridden 您的jTextField2.setText值已被覆盖
  • Your values low and high are not what you think they are 您的lowhigh值不是您认为的那样
  • Your values low and high are being changed at the same time/before your if statement runs 在您的if语句运行之前/同时更改您的lowhigh
  • The condition (con > con2) for your if statement is never satisfied, so the if is never invoked in the first place if语句的条件(con > con2)从不满足,因此从不首先调用if

    The best way to resolve this problem is for you to debug the remaining parts of your program, because the random number generation is clearly functional. 解决此问题的最佳方法是调试程序的其余部分,因为随机数生成显然可以正常工作。

  • 声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM