设计一个表示虚数的类,需要实现其中的构造函数、toString、euqals、hashCode这4个函数,并实现Comparable接口(按模比较大小)
设计一个表示虚数的类,需要实现其中的构造函数、toString、euqals、hashCode这4个函数,并实现Comparable接口(按模比较大小)
2013-07-13 16:47
程序代码:package examination;
public class ImaginaryNumber implements Comparable<ImaginaryNumber>
{
public ImaginaryNumber(int n, int i)
{
realnum = n;
imanum = i;
}
public ImaginaryNumber(int n)
{
realnum = n;
imanum = 0;
}
public String toString()
{
String s = realnum + "+" + imanum + "i";
return s;
}
public boolean equals(ImaginaryNumber i)
{
if (this.realnum == i.realnum)
{
if (this.imanum == i.imanum)
return true;
}
return false;
}
public int hashCode()
{
int h = 31;
h = 31 * h + realnum;
h = 31 * h + imanum;
return h;
}
private int realnum;
private int imanum;
@Override
public int compareTo(Imanum other)
{
double r = Math.sqrt(Math.pow(this.realnum, 2)
+ Math.pow(this.imanum, 2));
double o = Math.sqrt(Math.pow(other.realnum, 2)
+ Math.pow(other.imanum, 2));
if (r > o)
return 1;
if (r < o)
return -1;
return 0;
}
}
求大神帮忙看下哪里有问题!
2013-07-13 20:50
程序代码:package examination;
public class ImaginaryNumber implements Comparable<ImaginaryNumber>
{
public ImaginaryNumber(double re, double im)//带参数构造函数
{
realpart = re;
imaginarypart = im;
}
public double getRealpart()
{
return realpart;
}
public double getImaginarypart()
{
return imaginarypart;
}
public String toString()
{
String s =getRealpart() + "+" + getImaginarypart() + "i";
return s;
}
public boolean equals(ImaginaryNumber other)
{
if (this.getRealpart() == other.getRealpart())
{
if (this.getImaginarypart() == other.getImaginarypart())
return true;
}
return false;
}
public int hashCode()
{
return 3*new Double(getRealpart()).hashCode()+5*new Double(getImaginarypart()).hashCode();
}
private double realpart;
private double imaginarypart;
public int compareTo(ImaginaryNumber otherObject)
{
ImaginaryNumber other = (ImaginaryNumber) otherObject;
double r = Math.sqrt(Math.pow(this.getRealpart(), 2)
+ Math.pow(this.getImaginarypart(), 2));
double s = Math.sqrt(Math.pow(other.getRealpart(), 2)
+ Math.pow(other.getImaginarypart(), 2));
if (r > s)
return 1;
if (r < s)
return -1;
return 0;
}
}
2013-07-20 19:10