gpt4 book ai didi

Java setter、getter(掷骰子)

转载 作者:行者123 更新时间:2023-12-02 07:44:41 26 4
gpt4 key购买 nike

我有一些关于java的问题。代码中有两个问题(我将它们作为注释留下)。另外使用设置和获取方法的目的是什么?您能简单地解释一下吗?我是初学者。谢谢:)

public class Die
{
private final int MAX = 6;
private int faceValue;

public Die()
{
faceValue = 1;

//why do you set the faceValue as 1?
}

public int roll()
{
faceValue = (int)(Math.random() * MAX) + 1;
//Why do we use MAX instead of just number 6?

return faceValue;
}

public void setFaceValue (int value)
{
if (value > 0 && value <= MAX)
faceValue = value;
}

public int getFaceValue()
{
return faceValue;
}

public String toString()
{
String result = Integer.toString(faceValue);
return result;
}
}

最佳答案

首先,您应该正确使用代码示例标记,这样读起来很难看。使用 getter/setter 方法将阻止直接访问实例变量。这也称为数据隐藏或封装。至于你的问题,faceValue 被初始化为值 1,你通常在构造函数中进行初始化。第二个问题 Math.random 将生成一个 0-1 之间的数字,您将其乘以 6,结果是 0 到 5 之间的数字。因此,您添加 +1 以获得 1-6 的范围。

关于Java setter、getter(掷骰子),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3971648/

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