我该如何制作一个“骰子”?随机生成一个数字1-6每次使用它? [英] How can i make a "dice" that randomly generates a number 1-6 EACH time it is used?

查看:269
本文介绍了我该如何制作一个“骰子”?随机生成一个数字1-6每次使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我正在使用

 int die = (int)(6.0 * Math.random()) + 1;

这对我想要创建的循环不起作用。这是我正在使用的方法。

This does not work for the loop i am trying to create. This is the method i am using.

public void computerRoll()
{ 

 do { roll();
      System.out.println("Roll:"+ die);
      computerScore += die;
     } while (computerScore <= 20 && die >=2 && die <=6 );
     if (computerScore >=20)
        computerHold();

     if (die == 1)
        switchTurn();

 }

roll()方法只是简单地使用上一行代码在其中,int die =(int)(6.0 * Math.random())+ 1;我试过移动它甚至为它做一个占位符但如果我执行方法并且数字不是1,它只打印该数字直到它达到20。
我正在尝试创建一个骰子,每次使用时都会生成一个新数字。

The roll() method just simply has the previous line of code in it, "int die = (int)(6.0 * Math.random()) + 1;" i have tried moving it around or even making a place holder for it but if i execute the method and the number is not a 1, it just prints that number until it reaches twenty. I am trying to create a "dice" that will make a NEW number each time it is used.

推荐答案

看起来你的roll-method不是作为一个函数处理的。你需要返回roll()函数生成的值。

It seems like your roll-method is not handled as a function. You need to return the value generated by your roll() function.

试试这个:

int roll() {
    return (int)(6.0 * Math.random()) + 1;
}

然后:

public void computerRoll() { 

    do { 
        int die = roll();
        System.out.println("Roll:"+ die);
        computerScore += die;
     } while (computerScore <= 20 && die >=2 && die <=6 );
     if (computerScore >=20)
         computerHold();

     if (die == 1)
         switchTurn();

 }

这篇关于我该如何制作一个“骰子”?随机生成一个数字1-6每次使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆