gpt4 book ai didi

java - 掷骰子的方法

转载 作者:行者123 更新时间:2023-11-30 02:00:31 26 4
gpt4 key购买 nike

我目前正在做一些学习书中的练习,其中一项任务是:编写一个骰子类“Dice”,其值在 1-6 之间。还应该有一个选择随机值的构造函数,以及一个也选择随机值的方法 roll() 。还应该创建 getValue() 方法,该方法将用于检索显示的值。为此程序编写一个测试类。

编辑* 我将随机数发生器移至构造函数,将 roll 方法留空。当构造函数已经随机化时,我应该在 roll() 方法中做什么?

这是我到目前为止的代码:

public class Dice {

int value;
int currentRoll;

public Dice() {
Random rand = new Random();
this.value = 1;
this.currentRoll = rand.nextInt(6) + 1;
}

public int roll() {
Random rand = new Random();
this.currentRoll = rand.nextInt(6) + 1;
return this.currentRoll;
}

public int getValue() {
return this.currentRoll;
}
}

我不明白的是:为什么要在构造函数和 roll() 方法中随机选择值?另外,我错过了什么?

最佳答案

为什么在构造函数中选择一个随机值?嗯,坦白说,因为这是练习的要求。
他们为什么有这个要求?如果我不得不猜测,这是为了模拟这样一个事实:骰子总是有一些面朝上(即有一个值),无论你是否明确地滚动它,但如果你想要一个明确的答案,你'我必须询问这本书的作者他或她的想法。

您可以通过在构造函数中调用 roll 来实现此目的。另请注意,已初始化但从未使用过的 value 成员具有冗余:

public class Dice {
private int currentRoll;

//Constructor
public Dice() {
roll();
}

// methods...

关于java - 掷骰子的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53006869/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com