【发布时间】:2016-12-06 23:14:55
【问题描述】:
这个程序的目的是测试我创建的另一个程序。
它叫做ComplexNumber。这个类包含从加法、乘法、除法复数和其他东西的所有内容,它们都在方法中。老师希望我们创建一个测试类,这是我目前所拥有的。
我遇到的问题是调用 ComplexNumber 类的方法。例如:我尝试调用plus方法,该方法接受两个ComplexNumbers并将它们相加。到目前为止,我一直在使用交互面板测试这些方法,并且效果很好。我在交互面板中调用它们的方式是 first.plus(Second),这将给出最终值。
在测试课上,我很难调用这些方法。
我知道我需要类名。
我试过了:
ComplexNumber.first.plus(second)
但它没有用。
我该怎么做?
这是我的代码:
class TestComplexNumber
{
double real;
double imag;
public TestComplexNumber(double a, double b)
{
this.real=a;
if ((b<1000)&&(b>-1000))
this.imag=b;
else
{
this.imag=0;
System.out.println("The value you typed in for imag is <1000 or >-1000, value of imag is assigned the value of 0.");
}
}
public String toString()
{
double real,imag;
real=this.real;
imag=this.imag;
if (((real<0)||(real>0))&&(imag%1!=0))
{
if (roundThreeDecimals(imag)>0)
return ""+roundThreeDecimals(real)+"+"+roundThreeDecimals(imag)+"i";
else
return ""+roundThreeDecimals(real)+""+roundThreeDecimals(imag)+"i";
}
else if ((real%1!=0)&&(imag!=0))
return ""+roundThreeDecimals(real)+"+"+(int)imag+"i";
else if((real==0)&&(imag%1!=0))
return ""+imag+"i";
else if ((real==0)&&(imag !=0))
return ""+(int)imag+"i";
else if ((imag==0)&&(real!=0))
return ""+(int)real+"";
else if (((real<0)||(real>0))&&(imag<0))
return ""+(int)real+"-"+(int)Math.abs(imag)+"i";
else if((real!=0)&&(imag!=0))
return ""+(int)real+"+"+(int)imag+"i";
else
return "";
}
public static double roundThreeDecimals(double c)
{
double temp = c*1000;
temp = Math.round(temp);
temp = temp /1000;
return temp;
}
public static void main(String args[])
{
for(int i=0;i<1;i++)
{
//Testing decimal values
TestComplexNumber first=new TestComplexNumber((int)(Math.random()*100)-(int)(Math.random()*100),(Math.random()*100));
TestComplexNumber second=new TestComplexNumber((Math.random()*100),(Math.random()*100)-(int)(Math.random()*100));
//Testing whole values
TestComplexNumber third=new TestComplexNumber((int)(Math.random()*100)-(int)(Math.random()*100),(int)(Math.random()*100));
TestComplexNumber fourth=new TestComplexNumber((Math.random()*100)-(int)(Math.random()*100),(int)(Math.random()*100));
System.out.println(first);
System.out.println(second);
System.out.println(third);
System.out.println(fourth);
System.out.println("Test value for plus:"+first+second+" which added="+plus(second));
}
}
}
ComplexNumber 类的方法示例:
public ComplexNumber plus(ComplexNumber other) {
ComplexNumber sum= new ComplexNumber(this.real,this.getImag());
sum.real=(this.real)+(other.real);
sum.setImag((this.getImag())+(other.getImag()));
return sum;
}
【问题讨论】:
-
我有两个对象:double real 和 double imag,我不想发布我的 ComplexNumber 类
-
我的老师说我必须在新班级而不是 ComplexNumber 班级中创建测试程序。
-
我想要的是如何在另一个类中调用实例方法。
-
我从 ComplexNumber 类中放入了 plus 方法
-
你能告诉我我必须做什么,我不明白
标签: java class object methods complex-numbers