equals() 方法不起作用

equals() method not working

equals() 方法应该检查第一个盒子和立方体的尺寸是否相同。如何解决?它目前不起作用。

程序 returns 消息 "illegal start of type" 在 if。我是新手请帮忙

public class testNew
{

 public static void main (String []args)
 {
  Rectangle3 one = new Rectangle3(5,20);
  Box3 two = new Box3(4,4,4);
  Box3 three = new Box3(4,10,5);
  Cube3 four = new Cube3(4,4,4);

  showEffectBoth(one);
  showEffectBoth(two);
  showEffectBoth(three);
  showEffectBoth(four);
 }

  public static String showEffectBoth(Rectangle3 r)
 {
  return System.out.println(r);
 }

 boolean b = two.equals(four);

if (b == true)
{
 System.out.println("Box and cube have the same dimensions");
}


}


public class Rectangle3
{
// instance variables 
int length;
int width;

public Rectangle3(int l, int w)
{
 length = l;
 width = w;
}

public int getLength()
{
  return length;
}
public int getWidth()
{
  return width;
}
public String toString()
{
   return getClass().getName() + " - " + length + " X " + width;
}
public boolean equals(Rectangle3 obj) 
{
    if ((getLength().equals(obj.getLength()) && getWidth().equals(obj.getWidth())))
        return true;
    else
        return false;
    }

  }

这不是等于函数。行

boolean b = two.equals(four)

是非法的。它不在任何方法中,它引用在 main()!

中声明的变量

首先,关于你的编译错误,与equals()方法无关。这只是因为下面的所有代码都应该在您的主要方法中,因为它是您声明变量 twofour:

的唯一部分
boolean b = two.equals(four);

   if (b == true) {
        System.out.println("Box and cube have the same dimensions");
   }

另请注意,Rectangle3 class 不应与 testNew 在同一个文件中,因为两者都声明为 public,如果您想同时使用两者它们在同一个文件中然后你需要从其中一个(你不会用作文件名的那个)中删除 public 声明

Second,您的 equals() 方法在技术上是正确的(我想在功能上也是如此)但它不是您在此处的代码中包含的 equals() 方法, 因为这个属于 Rectangle3 而你在这里测试的 equals() 应该定义在 Box3Cube3

注意: 请注意,根据 assylias 的评论,因为 bboolean,所以不需要使用 if (b == true)if (b) 就足够了