我的目标是打印出复杂对象的数量(应该是2),但我的主要方法似乎不接受我的defObjCount类。我该怎么做才算复杂的对象?
public class Complex {
private double a = 0; // real numbers
private double b = 0; // imaginary numbers
private static int counter = 0;
public Complex(double a, double b){
this.a = a;
this.b = b;
counter++;
}
public void defObjCount(){
System.out.println(counter);
}
public boolean equals(Complex rhs){
return a == rhs.a && b == rhs.b;
}
public Complex multiply(Complex rhs){
return new Complex(a * rhs.a - b * rhs.b, b * rhs.a + a * rhs.b);
}
public String toString() {
return String.format("%.0f + %.0fi", a, b);
}
}
主要课程:
public class ComplexDriver{
public static void main(String[] args) {
Complex c1 = new Complex(1,2);
Complex c2 = new Complex(3, 4);
System.out.println(c1);
//boolean same = c1.equals(c2);
//Complex prod = c2.multiply(c1);
System.out.println(c1.equals(c2));
System.out.println(c1.equals(c1));
System.out.println(c1.multiply(c1));
System.out.println(c2.multiply(c2));
System.out.println("Number of Complex obj created: " + Complex.defObjCount());
}
}
答案 0 :(得分:1)
您的主要问题是defObjectCount
被声明为void
,这意味着它没有可以在任何地方使用的返回值。它还需要static
,以便您可以在不调用特定对象的情况下使用它。你最好这样写它。
public static int defObjCount(){
return counter;
}
答案 1 :(得分:0)
您的defObjCount()
方法只是打印,不返回任何内容。您可以将其返回类型更改为int
并返回计数器变量而不是打印它(如David的回答中所述)。
除此之外,您还可以这样做:
System.out.println("Number of Complex obj created: ");
c1.defObjCount(); //or c2.defObjCount();
c1.defObjCount()
将打印4。