gpt4 book ai didi

java - 构造函数方法仅在其他变量为静态时有效,并且对第一个对象不起作用

转载 作者:行者123 更新时间:2023-12-01 10:57:37 25 4
gpt4 key购买 nike

我有两个类,一个称为士兵,一个称为战场,士兵可以在战场参数指定的战场尺寸内的任何位置生成

将士兵对象放在 x 和 y 轴上的变量是:

private double xPos;
private double yPos;

那些属于士兵类别

在战场上生成Soldier对象的方法是

public Soldier(double speed) {
this.speed = speed;
xPos = (int) (Math.random() * Battlefield.getX());
yPos = (int) (Math.random() * Battlefield.getY());
}

以及战场类内

private static double x;
private static double y;

public static double getY() {
// TODO Auto-generated method stub
return y;
}

public static double getX() {
// TODO Auto-generated method stub
return x;
}

主要方法,

public class Battle { 
//Main method where three battles are run.
public static void main(String[] args) {
Battlefield k = new Battlefield(100, 100);
Battlefield b = new Battlefield(100, 100);
Battlefield c = new Battlefield(100, 100);
}
}

我遇到的问题是这样做会导致第一个对象没有任何坐标,之后的所有内容看起来都很好,但为什么?

最佳答案

从主类来看,您似乎希望每个 Battlefield 都有自己的状态...所以不要将 Battlefield.x 和 Battlefield.y 设为静态,否则它们都会相同。

战地的构造函数在哪里?

关于java - 构造函数方法仅在其他变量为静态时有效,并且对第一个对象不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33533935/

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