基本随机滚动骰子Java [英] Basic Random Rolling Dice Java

查看:248
本文介绍了基本随机滚动骰子Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个方法rollDice(int number,int nSides),它返回用nSides边滚动数字骰子的总结果。

I am trying to write a method rollDice(int number, int nSides) which returns the total result of rolling the number dice with nSides sides.

所以例如rollDice(3,6)应返回滚动3个六面骰子的结果(加上3到18之间的数字)。

So for example rollDice(3, 6) should return the result of rolling 3 six-sided dice (adding to a number between 3 and 18 inclusive).

下面的方法返回负数时我输入 int number 我需要做些什么来解决这个问题?

Below method returns negative numbers when I type 1 for int number what do I need to do to fix this?

public static  int rollDice(int number, int nSides) {
    int num = 0;
      if(nSides >=3)
    {
      for(int i = 0; i < number; i++){
       Random  r = new Random(); 
       int roll = r.nextInt();
       num = num + (roll % nSides)+1;

      }
    }
      else{
          System.out.println("Error num needs to be from 3");

    }
    return num; 
} 


推荐答案

你只需要初始化<每次code> Random r 和 int roll ,所以我已将它们从循环中删除。 nextInt(int)方法从0中选择一个整数,但不包括int。这被称为0(包括)到int(不包括),因此您必须添加1以调整到模具的范围。你似乎已经知道,虽然我不知道你为什么使用%。使用*乘以会给你所有骰子的相同数字,我不相信你的意思。以下是您班级的一种可能实现:

You only need to initialize Random r and int roll once each so I have removed them from the loop. The nextInt(int) method picks an integer from and including 0 to but not including the int. This is known as 0 (inclusive) to int (exclusive), so you have to add 1 to adjust the range to the die. You seem to have known that though I don't know why you used %. Using * to multiply would give you the same number for all the dice which I don't believe you mean to do. Here is one possible implementation of your class:

import java.util.Random;

public class Dice {

    public static  int rollDice(int number, int nSides)
    { 
        int num = 0;
        int roll = 0;
        Random  r = new Random(); 
        if(nSides >=3) 
        { 
            for(int i = 0; i < number; i++)
            { 
                roll = r.nextInt(nSides)+1;
                System.out.println("Roll is:  "+roll);
                num = num + roll; 
            } 
        } 
        else
        { 
            System.out.println("Error num needs to be from 3"); 
        } 
        return num;  
    } 

    public static void main(String[] args)
    {
        System.out.println("Total is: "+rollDice(3, 6));
    }
}
/*
Roll is:  4
Roll is:  1
Roll is:  2
Total is: 7
*/

这篇关于基本随机滚动骰子Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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