gpt4 book ai didi

java - 计算一个方法被调用的次数?

转载 作者:行者123 更新时间:2023-11-29 10:14:57 25 4
gpt4 key购买 nike

我正在尝试计算方法被调用的次数。我现在有 3 个类,Circle.java、Picture.java 和 PictureTest.java

circle.java里面有;

public class Circle
{
private int diameter;
private int xPosition;
private int yPosition;
private String color;
private boolean isVisible;
private int instances;

/**
* Create a new circle at default position with default color.
*/
public Circle()
{
diameter = 30;
xPosition = 20;
yPosition = 60;
color = "blue";
isVisible = false;
instances = 0;
instances++;
System.out.println(instances);
}

在Picture.java中:

public class Picture
{
private Circle sun;

/**
* Constructor for objects of class Picture
*/
public Picture()
{
// nothing to do... instance variables are automatically set to null
}

/**
* Draw this picture.
*/
public void draw()
{
sun = new Circle();
sun.changeColor("yellow");
sun.moveHorizontal(180);
sun.moveVertical(-10);
sun.changeSize(60);
sun.makeVisible();

sun = new Circle();
sun.changeColor("yellow");
sun.moveHorizontal(180);
sun.moveVertical(-10);
sun.changeSize(60);
sun.makeVisible();

sun = new Circle();
sun.changeColor("yellow");
sun.moveHorizontal(180);
sun.moveVertical(-10);
sun.changeSize(60);
sun.makeVisible();
}

PictureTest.java 是 main 所在的地方:

public class PictureTest
{
public static void main(String[] args)
{
Picture p = new Picture();
p.draw();

}
}

当我运行它时,它打印的不是 3 因为有三个太阳,而是打印:

1
1
1

我不完全确定为什么会这样,但我认为这可能与我从 Circle 类打印的事实有关,所以每次创建圆时它都会打印 1。我试过更改它,以便它从 PictureTest 中的主要打印实例,但我无法让它工作。

谢谢!

最佳答案

instances = 0;
instances++;

instances 将始终等于 1

您需要做的是将instances 设为static 变量。

public class Circle
{
public static int instances = 0;
}

然后在你的构造函数类中

instances ++;

关于java - 计算一个方法被调用的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20428025/

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