【发布时间】:2013-12-08 04:10:38
【问题描述】:
所以我正在制作一个可以创建和滚动骰子、返回值和大小的骰子类。我试图弄清楚如何告诉程序已经创建了多少,以便我可以根据有多少做出不同的响应。 IE 我希望 printDie 的响应是 Die Value: 5 如果只有一个 die,Die 1 Value: 5 如果有多个。
这是我目前的代码。
package com.catalyse.die;
import java.util.Random;
public class Die
{
// instance variables
private int myDieValue;
private int myDieSides;
private Random myRandom;
// Dice Class Constructors
public Die()
{
this.myDieValue = 1;
this.myDieSides = 4;
}
public Die(int numSides)
{
if ((numSides < 4) || (numSides > 100)) {
System.out.println("Error! You cannot have more than 100 sides or less than four!");
System.exit(0);
}
else {
myDieSides = numSides;
}
}
// getter methods
public int getDieSides()
{
return myDieSides;
}
public int getDieValue()
{
return myDieValue;
}
// setter methods
private void setDieSides(int newNumSides)
{
myDieSides = newNumSides;
}
public void rollDie()
{
Random rand = new Random();
int i = (rand.nextInt(myDieSides) + 1);
myDieValue = i;
}
public void printDie(int dieNum)
{
if (dieNum == 1) {
System.out.println("Die Value: "+myDieValue);
}
else {
System.out.println("Die "+dieNum+" Value: "+myDieValue);
}
}
}
【问题讨论】:
-
注意:Java 没有解构函数,因此通过使用静态字段,如果删除一个字段,计数将不会反映此更改。
-
你提供的信息很不错,但我得问你,你说的一个被删除到底是什么意思?由于没有析构函数,所以没有删除。我猜你的意思是说,垃圾收集,可能? :)
标签: java object methods constructor