好吧,我完全是个初学者,只是在课堂上学习。谁能告诉我我在做什么错?当我运行此代码时,应该告诉我myMonkey和myFavoriteMonkey是相同的颜色...但是我一直得到输出的空值...

我在另一个Java页面上找到了这个(?)

public class Monkey2 {
   private String color;
   private int weight;

   public void setColor(String color)  {
      this.color = color;
   }

   public String getColor(){
      return color;
   }

   public void setWeight(int w){
      this.weight = weight;
   }

   public int getWeight(){
      return weight;
   }

   public void swing()  {
      System.out.println("Swinging");

   }
}


这在另一个页面上

public class MonkeyApp  {
   public static void main(String[] args) {
      Monkey2 myMonkey = new Monkey2();
      Monkey2 myMonkey2 = new Monkey2();
      Monkey2 myFavoriteMonkey = myMonkey;

      String myFavoriteMonkeyColor = "black";
      int myMonkeyWeight = 75;

      myMonkey.setWeight(myMonkeyWeight);

      myFavoriteMonkey.swing();
      System.out.println("myMonkey: " + myMonkey +
         " color: " + myMonkey.getColor() +
          " weight: " + myMonkey.getWeight());
      System.out.println("myMonkey2: " + myMonkey2 +
         " color: " + myMonkey2.getColor() +
         " weight: " + myMonkey2.getWeight());
      System.out.println("myFavoriteMonkey: " + myFavoriteMonkey +
         " color: " + myFavoriteMonkey.getColor() +
         " weight: " + myFavoriteMonkey.getWeight());
   }
}

最佳答案

您的setWeight(int)有一个错误;您传入w,但在作业中使用weight。我很确定你想要

public void setWeight(int w){
    // this.weight = weight;
    this.weight = w;
}


另外,您可能应该在某个地方致电myMonkey2.setWeight()。并且不要忘记在某个地方也调用myMonkey.setColor(myFavoriteMonkeyColor)myMonkey2.setColor()

10-05 18:21