java骰子,基本随机滚动骰子Java

这篇博客讨论了如何修正rollDice方法,确保在掷骰子时不会得到负数结果。问题出在nextInt方法的使用上,通过在循环外初始化Random对象,并正确调整nextInt的范围,可以解决这个问题。提供的代码示例展示了修复后的rollDice方法,它现在能正确地返回3到18之间的总和。
摘要由CSDN通过智能技术生成

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.

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).

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;

}

解决方案

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

*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值