gpt4 book ai didi

java - 计算现有对象的数量

转载 作者:行者123 更新时间:2023-12-02 07:47:29 25 4
gpt4 key购买 nike

所以我正在制作一个骰子类,它可以创建和滚动骰子,返回值和大小。我试图弄清楚如何告诉程序已经创建了多少个,以便我可以根据有多少个做出不同的响应。 IE 如果只有一个骰子,我希望 printDie 的响应为 Die Value: 5,如果有多个骰子,则为 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);
}
}

}

最佳答案

您的类中可以有静态字段,该字段可以在构造函数中始终递增。之所以应该是静态的,是因为静态字段由类的所有实例共享,因此不会为每个实例创建该字段的本地副本您创建的实例的数量。

private static int counter = 0;
public Die()
{
counter++;
// Other stuffs
}
// Have a getter method for the counter so that you can
// get the count of instances created at any point of time
public static int getCounter() {
return counter;
}

然后你可以像这样在你的调用方法中调用上面的方法

void someMethodInAnotherClass() {
int instanceCount = Die.getCounter(); // You need to call static method using the Class name
// other stuffs.
}

关于java - 计算现有对象的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20159104/

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