我需要能够检查一个构造函数的变量a,b和c是否等于另一个构造函数(二次q)的a,b和c。我感到我的副本构造函数可能是错误的,这也可能是问题所在。我正在尝试通过最后一种方法来完成此任务。忽略我现在所拥有的东西,我确定这是完全错误的。我将不胜感激。这是我到目前为止的内容:
import java.util.Scanner;
public class Quadratic
{
// instance variables - replace the example below with your own
private double a;
private double b;
private double c;
/**
* Assignment constructor
*/
public Quadratic(double aIn, double bIn, double cIn)
{
a=aIn; b=bIn; c=cIn;
}
/**
* Copy constructor of class Quadratic for objects
*/
public Quadratic(Quadratic q)
{
a=q.a;b=q.b;c=q.c;
}
/**
* Default constructor - uses Scanner class.
*/
public Quadratic()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a: ");
double a=in.nextDouble();
System.out.println("Enter b: ");
double b= in.nextDouble();
System.out.println("Enter c: ");
double c= in.nextDouble();
}
/**
* Returns an expression for the quadratic, i.e., 1.0x^2 + 3.0x + 2.0
*/
public String toString()
{
return a+"x^2 + "+b+"x + " + c;
}
/**
* Returns true if a, b, and c all match for this & q; false otherwise.
*/
public boolean equals(Quadratic q)
{
if (Quadratic(q).equalsQuadratic(a,b,c))
return true;
else
return false;
}
}
答案 0 :(得分:1)
提示。如果使用IntelliJ IDEA,则右键单击并生成...-> equals()和hashCode();。
public final class Quadratic {
private final double a;
private final double b;
private final double c;
public Quadratic(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
public Quadratic(Quadratic quadratic) {
this(quadratic.a, quadratic.b, quadratic.c);
}
@Override
public String toString() {
return a + "x^2 + " + b + "x + " + c;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof Quadratic))
return false;
Quadratic quadratic = (Quadratic)obj;
return Double.compare(quadratic.a, a) == 0 &&
Double.compare(quadratic.b, b) == 0 &&
Double.compare(quadratic.c, c) == 0;
}
@Override
public int hashCode() {
return Objects.hash(a, b, c);
}
}
this
访问类变量,但不访问mehtod参数Scanner
应该关闭Scanner
,这不属于该类。在客户端代码中使用它,然后调用构造函数double
值应与Double.compare
equals() + hashCode()
-这是必须具备的(好吧,hashCode()
可能没有用,如果您不打算将此类用作哈希映射中的键,但仍然-这应该是自动的)equals() + hashCode()
时,请注意规范。