Monday, May 24, 2010

How to return multiple integers with a single return statement in java?

Once again i come to the yahoo answers community for help with my java homework. The goal is to make a 2 class program where one class will have a menu to choose options, while the other has a constructor to make 2 ints of a complex number (a+bi where i = square root -1). I have most of the program done and running but i need to make a method in the program with the constructor to add the complex numbers. This means ill run somthing like the following:


public ?????????? AddComp(ComplexNumber other){tempvar =this.real + other.real;


tempvar2 = this.complex + other.complex;


return (????????????????);}


Now my question is how do i return those 2 ints to the main class and method? can you return 2 values in one method or do i have to make seperate methods for the real and complex parts? and if i could do multiple return values, what do i declarethe method as?


Thanks a ton for the help.


Dan

How to return multiple integers with a single return statement in java?
Hey Dan, you would return an object which would contain both the integers. What class is "this"? I assume it is something like class ComplexNumber which contains two fields "int real" and "int complex". I that is the case then you would create a ComplexNumber in the method and return that. I haven't done a lot of Java programming but this is how its done in C++





Class ComplexNumber {


public:


ComplexNumber addComp(ComplexNumber other) {


cn = new ComplexNumber();


cn.real = this.real + other.real;


cn.complex = this.complex + other.complex





return cn;


}





int real;


int complex;


}











int main() {


ComplexNumber a, b, c;





c = a.addComp(b);


}








Hope that helps some.


No comments:

Post a Comment