【问题标题】:add two complex numbers, but the result will be returned to another object of the same class in java两个复数相加,但是结果会返回给java中同一个类的另一个对象
【发布时间】:2014-08-23 21:50:23
【问题描述】:

从方法返回对象

import java.util.Scanner; 
class ComplexNos 
{ 
 private int x,y; 
 ComplexNos(int a,int b) 
{ 
 x=a; 
 y=b; 
}  
ComplexNos add (ComplexNos a) //method Returns an object 
{ 
 ComplexNos c=new ComplexNos();// iam getting an error here 
 c.x=x+a.x; 
 c.y=y+a.y; 
 return c; 
} 
void display() 
{ 
 if(y>=0) 
 System.out.println(x+"+i"+y); 
 else 
 System.out.println(x + "" + y +"i"); 
} 
} 
class ObjectReturn 
{ 
 public static void main(String args[]) 
{ 
 int a,b; 
 Scanner sc=new Scanner(System.in); 
 System.out.println("Enter real and imaginary part of a complex number:"); 
 a=sc.nextInt(); 
 b=sc.nextInt(); 
 ComplexNos c1=new ComplexNos(a,b); 
 System.out.println("Enter real and imaginary part of another complex 
 number:"); 
 a=sc.nextInt(); 
 b=sc.nextInt(); 
 ComplexNos c2=new ComplexNos(a,b); 
 ComplexNos c3 = new ComplexNos();//iam getting an error here
 c3=c1.add(c2); //Storing new value in object c3 
 c3.display();  
System.out.println("Value of the 1st object is: "); 
c1.display(); 
System.out.println("Value of the 2nd object is: "); 
c2.display(); 
} 
}

output:

    ObjectReturn.java:12: error: constructor ComplexNos in class ComplexNos cannot b
    e applied to given types;
     ComplexNos c=new ComplexNos();
                  ^
      required: int,int
      found: no arguments
      reason: actual and formal argument lists differ in length
    ObjectReturn.java:39: error: constructor ComplexNos in class ComplexNos cannot b
    e applied to given types;
     ComplexNos c3 = new ComplexNos();
                     ^
      required: int,int
      found: no arguments
      reason: actual and formal argument lists differ in length
    2 errors

我是初学者,所以我无法理解问题所在。

【问题讨论】:

    标签: java compiler-errors


    【解决方案1】:

    问题是您尝试使用 ComplexNos 对象没有的构造函数来实例化它。

    当你打电话时

    ComplexNos c=new ComplexNos();
    

    它正在寻找一个看起来像的构造函数

    ComplexNos() { 
        //some code
    }
    

    但它在您的代码中找不到。

    解决方案是创建一个默认的无参数构造函数,如上面的构造函数,或者重构你创建的 c 变量以使用你已经拥有的构造函数(比如那里有两个数字的构造函数)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-09
      • 2014-11-19
      • 1970-01-01
      • 2017-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多