猿问

如何正确引用此代码中的宝石重量?

我如何在这段代码中引用石头的重量,以便我可以在我的unlockChest方法中使用它?我基本上试图将用户从对象 new Stone()) 输入的权重相加,因此它 == 组合了用户在 Chest() 构造函数中输入的值。我知道这是错误的,但我尝试了 jar1.weight,它说它不是变量。



public class Stone

{


    private String name;

    private int weight;


    public Stone()

    {

        System.out.print("Enter stone name: ");

        name = Global.keyboard.nextLine();


        System.out.print("Enter stone weight: ");

        weight = Global.keyboard.nextInt();

        Global.keyboard.nextLine();

    }

}



public class Jar

{


    private int position;

    private Stone stone;



    public Jar()

    {

        position = 0;

        stone = null;

    }


    public Jar(int initPos, Stone stone)

    {

        position = initPos;

        this.stone = stone;

    }


public class Ground

{

    private Jar jar1;

    private Jar jar2;

    private Jar jar3;

    private Player player;

    private Chest chest;


    public Ground()

    {

      player = new Player();


      jar1 = new Jar(1, new Stone());

      jar2 = new Jar(2, new Stone());

      jar3 = new Jar(3, new Stone());


      chest = new Chest()


    }


    public boolean ChestUnlocked()

    {

        if (jar1.weight + jar2.weight + jar3.weight == chest.combination) //the main problem

         return true;

        else

         return false;

    }



public class Chest

{


    public int combination;

    private int position;

    private Jar jar1;

    private Jar jar2;

    private Jar jar3;


    public Chest()

    {

        System.out.print("Enter chest combination (5-10): ");

        combination = Global.keyboard.nextInt();

        Global.keyboard.nextLine();



        position = 4;

        jar1 = new Jar(4, null);

        jar2 = new Jar(4, null);

        jar3 = new Jar(4, null);

    }


呼啦一阵风
浏览 125回答 3
3回答

炎炎设计

建议:在每个类中添加 getter/setter,以便您可以使用 getter 和 setter 访问私有变量。Stone() 是 Jar() 中的私有对象。假设 Jar() 中有 getStone() 返回: this.stone; 你可以做if (jar1.getStone().getWeight() + jar2.getStone().getWeight() + jar3.getStone().getWeight() == chest.combination) //the main problem还要确保在尝试访问可为 null 的对象中的方法之前检查 null 对象(例如,如果 jar1 Stone 为 null,则 jar1.getStone().getWeight() 将失败)

芜湖不芜

Stone 可能还有 Stone 类中的权重属性是私有的。为了正确使用它们,我建议您为您的类实现 getter 方法。实现 getter 后,您可以使用如下方式调用它们:jar1.getStone().getWeigth()其中 getStone() 是 Jar 类中的 getter,getWeight() 是 Stone 类中的 getter。

杨魅力

您需要Stone通过添加 getter 来公开权重public int getWeight() {    return weight;}然后你可以用类似的方法使用它Jarpublic int getWeight() {    if (stone == null) {        return 0;    }    return stone.getWeight();}那么你的方法就是public boolean ChestUnlocked() {    if (jar1.getWeight() + jar2.getWeight() + jar3.getWeight() == chest.combination) {         return true;    }     return false;}假设 Jar 对象和 Chess 对象永远不为 null
随时随地看视频慕课网APP

相关分类

Java
我要回答