我需要能够检查一个构造函数中的变量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;
}
}
提示。如果使用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()
时,请注意规范