gpt4 book ai didi

java - 构造函数创建多个变量,如何通过其他方法返回它们?

转载 作者:行者123 更新时间:2023-12-01 15:28:43 25 4
gpt4 key购买 nike

public class Game {

public Game(
boolean createstage, //For sorting purposes
int slength,
int sheight,
boolean createplayer,
int plength,
int pheight,
boolean playersprite,
BufferedImage psprite,
boolean defaultcontrols,
String pcontrols,
boolean test
) {
if(test == true) { //if test is true, test
new Test();
}else{ //otherwise create a stage is createstage is true and
if(createstage == true) {
StageObj gamestage = new StageObj(slength, sheight);
}
if(createplayer==true) {
PlayerObj player = new PlayerObj(plength, pheight, psprite, pcontrols);
}
}
}

public Game() {
new StageObj(100, 100);
new PlayerObj(10, 10);
}

public StageObj givestageobj() {
return gamestage;
}

public PlayerObj giveplayerobj() {
return player;
}

}

我的构造函数的代码和两个旨在返回构造函数中创建的变量的变量也是如此。问题是方法 Giveplayerobj 和 Givestageobj 都找不到变量 gamestage 和player。这是有道理的,但是我如何在构造函数中创建变量,然后以某种方式将它们传递给 Giveplayerobj() 和 Givestageobj() 变量,以便理论上有人可以转到 Game.giveplayerobj() ,它返回在构造函数中创建的playerobj?

谢谢

-JXP

最佳答案

您需要将它们声明为类属性,而不是在构造函数内才能正常工作。因此,您的代码应如下所示。

变化:

  1. 我添加了两个类变量 StageObj 和 PlayerObj,因为您已经为它们准备好了 getter。
  2. 从构造函数内部删除了这两个变量的声明。
  3. 添加了对覆盖默认构造函数的赋值。 (可能是您试图使用默认构造函数实现的目标)

    public class Game {

    private StageObj gamestage = null;
    private PlayerObj player = null;

    public Game(
    boolean createstage, //For sorting purposes
    int slength,
    int sheight,
    boolean createplayer,
    int plength,
    int pheight,
    boolean playersprite,
    BufferedImage psprite,
    boolean defaultcontrols,
    String pcontrols,
    boolean test
    ) {
    if(test == true) { //if test is true, test
    new Test();
    }else{ //otherwise create a stage is createstage is true and
    if(createstage == true) {
    gamestage = new StageObj(slength, sheight);
    }
    if(createplayer==true) {
    player = new PlayerObj(plength, pheight, psprite, pcontrols);
    }
    }
    }

    public Game() {
    gamestage = new StageObj(100, 100);
    player = new PlayerObj(10, 10);
    }

    public StageObj givestageobj() {
    return gamestage;
    }

    public PlayerObj giveplayerobj() {
    return player;
    }

    }

关于java - 构造函数创建多个变量,如何通过其他方法返回它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9840480/

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