gpt4 book ai didi

java - 首先Java : Target Random number is always zero

转载 作者:行者123 更新时间:2023-12-01 18:29:24 24 4
gpt4 key购买 nike

我一直在尝试这段代码,使用 math.random() 生成的目标数字总是为零。代码有问题吗?请帮忙。我尝试了很多次,但每次尝试目标随机数始终为零。

public class Player {
int number;

public void guess()
{
number = (int) (Math.random()*10);
}
}



public class GuessGame {
Player p1;
Player p2;
Player p3;

public void startGame()
{
p1 = new Player();
p2 = new Player();
p3 = new Player();

int targetNumber;
targetNumber = (int) Math.random() * 10 ;
System.out.println("The target number is "+ targetNumber);


while(true)
{
p1.guess();
p2.guess();
p3.guess();

int guessp1 = p1.number;
int guessp2 = p2.number;
int guessp3 = p3.number;

System.out.println("Number guessed by player p1 is "+ guessp1);
System.out.println("Number guessed by player p2 is "+ guessp2);
System.out.println("Number guessed by player p3 is "+ guessp3);

boolean isp1 = false;
boolean isp2 = false;
boolean isp3 = false;

if(targetNumber==guessp1)
isp1 = true;
if(targetNumber==guessp2)
isp2 = true;
if(targetNumber==guessp3)
isp3 = true;
if(isp1||isp2||isp3)
{
System.out.println("player1 got it right? " + isp1);
System.out.println("player2 got it right? " + isp2);
System.out.println("player3 got it right? " + isp3);
System.out.println("Game Over!!!");
break;
}
else
{
System.out.println("All Wrong!! Play Again..");
}
}

}

}

public class GameLauncher {
public static void main(String[] args)
{
GuessGame game = new GuessGame();
game.startGame();
}
}

最佳答案

问题出在下面一行

targetNumber = (int) Math.random() * 10 ;

Math.random() 返回 0(包括)到 1(不包括)之间的 double 值,并且您将其转换为 int,在乘法之前将其变为零。

使用

targetNumber = (int) (Math.random() * 10 );

或者更好地使用

Random random = new Random();
number = random.nextInt(10);

关于java - 首先Java : Target Random number is always zero,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24969942/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com