简体   繁体   English

要设置限制(1或2)时需要一个随机数?

[英]How to set limits (1 or 2) When wanting a random number?

I am attempting to create a method where a user predicts if a simulated coin toss will be heads or tails. 我正在尝试创建一种方法,用户可以预测模拟的抛硬币是正面还是反面。 I am having trouble getting the random number to assign to just 1 or 2 (for heads of tails). 我很难将随机数分配给1或2(对于首尾)。 I believe my attempt(code below) is giving me 0, 1 and 2. 我相信我的尝试(下面的代码)给了我0、1和2。

public static void coinToss(String call){
        //setting up random
        Random random = new Random();

        //set user guess to numeric value
        int guessNo=0;


        if (call.equalsIgnoreCase("heads")){
            guessNo=1;
        }else if (call.equalsIgnoreCase("tails")){
            guessNo=2;
        }else System.out.println("Invalid. Enter either heads or tails");

        //setting result for coin toss 
        **int result = random.nextInt(2);**
        System.out.println("Trace: numberic result is:" + result);

        //if...else statement to print results of coin toss
        if (result==1){
            System.out.println("Result: heads");
        }else if (result==2){
            System.out.println("Result: Tails");
        }else System.out.println("Invalid result");

        if (guessNo==result){
            System.out.println("Guess Correct");
        }else System.out.println("Guess incorrect");

    }//method end

I am a relative java newbie (obviously!) so Many thanks in advance for any help! 我是相对的Java新手(很明显!),非常感谢您的帮助!

The answers suggesting adding one to the nextInt(2) result are correct, but may not be the right long term strategy. 暗示将一个加到nextInt(2)结果的答案是正确的,但可能不是正确的长期策略。 In many ways, Java prefers sequences of numbers to start, whenever possible, at 0. For example, array index values run from 0 through length-1. 在许多方面,Java都希望数字序列尽可能在0处开始。例如,数组索引值从0到length-1。

It may be better to change your internal encoding of the heads/tails to use [0,1] rather than [1,2], and use the nextInt result directly. 最好将头/尾的内部编码更改为使用[0,1]而不是[1,2],然后直接使用nextInt结果。

int result = (random.nextInt(2))+1; is what you might want to try. 是您可能想尝试的。

As documented, Random::nextInt supplies a random number between 0 (inclusive) and the specified upper limit (exclusive). 如记录所示, Random::nextInt提供一个介于0(含)和指定上限(不含)之间的随机数。 You must therefore first obtain a random number from the range [0,2> and then add 1 to that. 因此,您必须首先从[0,2>范围内获得一个随机数,然后将其加1。

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

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