簡體   English   中英

equals()方法不起作用

[英]equals() method not working

equals()方法應檢查第一個框和多維數據集的尺寸是否相同。 如何解決? 當前不起作用。

程序在if處返回消息"illegal start of type" 我是這個PLZ幫助的新手

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;
    }

  }

首先 ,關於您遇到的編譯器錯誤,它與equals()方法無關。 這僅僅是因為下面的所有代碼都應位於main方法內,因為這是您聲明變量twofour的唯一部分:

boolean b = two.equals(four);

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

還要注意, Rectangle3類不應該與testNew放在同一個文件中,因為它們都被聲明為public ,如果要在同一個文件中使用它們兩者,則需要從其中一個中刪除public偏斜(一個您將不會用作文件名)

其次 ,您的equals()方法在技術上是正確的(我從功能上也想),但這不是您的代碼中包含的equals()方法,因為該代碼屬於Rectangle3而您在此處測試的equals()應該定義在Box3Cube3

注意:請注意,根據assylias的評論,由於bboolean因此無需使用if (b == true) ,只要if (b)就足夠了

它不是equals函數。

boolean b = two.equals(four)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM