如何在此代码中引用石头的重量,以便可以在我的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);
}
最佳答案
Stone以及Stone类中的weight属性可能是私有的。为了正确使用它们,我建议您为类实现getter方法。实现吸气剂后,您可以使用类似以下内容的称呼:
jar1.getStone().getWeigth()
其中getStone()是Jar类中的吸气剂,而getWeight()是Stone类中的吸气剂。