如何解决当我清楚地覆盖相等方法时,我似乎无法弄清楚为什么我总是变得真实
我正在尝试解决这个问题,但似乎无法正确比较。
当我在运行时尝试设置代码时,结果最终会在我需要它生成错误测试时变为 True。广泛的测试表明它总是正确的,我不知道如何在它上面产生错误。
import java.util.Scanner;
public class LandTract
{
// instance variables
private static double length,width,area;
/**
* Constructor for objects of class LandTract
*/
public LandTract(double length,double width,double area)
{
// initialise instance variables
length = 0;
width = 0;
}
public LandTract(double length,double width)
{
this.length = length;
this.width = width;
}
public void setLength(double length)
{
this.length = length;
}
public double getLength()
{
return length;
}
public void setWidth(double width)
{
this.width = width;
}
public double getWidth()
{
return width;
}
public double getArea()
{
return area = length * width;
}
public String toString()
{
String str = "Length: " + length + "\nWidth: " + width;
return str;
}
public boolean equals(Object obj)
{
LandTract land = (LandTract) obj;
if (this.length != land.length)
return false;
if (this.width != land.width)
return false;
if (this.area != land.area)
return false;
return true;
}
public static void main(String[] args)
{
Scanner key = new Scanner(system.in);
System.out.print("Enter the length of the first tract of land: ");
length = key.nextDouble();
key.nextLine();
System.out.print("Enter the width of the first tract of land: ");
width = key.nextDouble();
key.nextLine();
LandTract land1 = new LandTract(length,width);
System.out.println("The area of the first tract of land is " + land1.getArea());
System.out.println();
System.out.print("Enter the length of the second tract of land: ");
length = key.nextDouble();
key.nextLine();
System.out.print("Enter the width of the second tract of land: ");
width = key.nextDouble();
key.nextLine();
LandTract land2 = new LandTract(length,width);
System.out.println("The area of the second tract of land is " + land2.getArea());
System.out.println();
if (land1.equals(land2))
System.out.println("Both tracts of land are the same size.");
else
System.out.println("They are different sizes.");
}
}
解决方法
令人困惑且具有讽刺意味的错误评论的最佳示例:
// instance variables
private static double length,width,area;
当您:
-
(真的)引入实例变量:
private double length,area;
-
修复 main 方法中的编译器问题(通过声明具有相同标识符的局部变量......没有好的风格但很快):
public static void main(String[] args) { double length,width; // ... }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。