Head First Java:目标随机数始终为零

时间:2014-07-26 10:14:16

标签: java

我一直在尝试这段代码,使用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();
    }
}

5 个答案:

答案 0 :(得分:3)

问题出在以下行

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

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

使用

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

或更好地使用

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

答案 1 :(得分:1)

由于operator precedence,首先使指定表达式中的第一个项等于0(因为Math.random返回一个值<0)。您可以使用括号来首先乘以数字

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

Boris said,只需使用nextInt

中的java.util.Random

答案 2 :(得分:0)

你应该写

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

这是因为你正在做的事情是将Math.random()生成的数字转换为int为零,然后将其重新分解为10

答案 3 :(得分:0)

您使用的是Math.random()状态

返回带有正号的double值,大于或等于0.0且小于1.0。

您正在将结果转换为int,它返回值的整数部分,即0。

然后1 + 0 - 1 = 0.

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

考虑使用Random

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

答案 4 :(得分:0)

使用Random类生成随机数: 请尝试以下代码:

    int targetNumber; 
    targetNumber = new Random().nextInt(100) ;