# Complex number class in JAVA

1. Aug 10, 2013

### CAF123

1. The problem statement, all variables and given/known data
Create a class which contains the following:
a)instance variables for the complex number. For x+yi, x and y are the variables.
b)constructor to initialize these variables.
c)methods to return the real and imaginary parts of the complex number
d)method to compute the magnitude of the complex number
e)method to convert complex number to a string (so it can be printed in form {x,y})
f)static method to take 2 complex numbers and return the sum as another complex number
g)static method to take 2 complex numbers, a and b, and return a*b as a third complex number.

3. The attempt at a solution
I have attempted steps a) - d) so far. My method for d) returns errors in the terminal so it is not correct. I don't really understand what e) means.
Code (Text):

class Complex {

double x;
double y; //instance variables for the complex number

Complex() {
this.x = "";
this.y = "";
}

Complex(double x, double y) {
this.x = x;
this.y = y; //constructor to initialise these variables

}

double getX() {
return this.x; //getter method for x, the real component of the complex number
}
double getY() {
return this.y; //getter method for y, the imaginary part of the complex number.
}

double mag;

void magnitude(double mag) {
this.mag = this.Math.sqrt(Math.pow(double x,2) + Math.pow(double y,2)); //method to compute magnitude of number
}

}

2. Aug 10, 2013

### Zondrina

Both of your constructors are incorrect. For the first one, you cannot assign string values to a double. For the second one, java is getting confused because of your parameters. Switch it to :

Code (Text):
public Complex(double _x, double _y) {
x = _x;
y = _y; //constructor to initialize these variables
}

Also, you don't need to call double mag; outside of the magnitude function. Delete it.

You should make the return type of your magnitude function a double. So you can make this happen :

Code (Text):
public double magnitude() {
return Math.sqrt(Math.pow(x,2) + Math.pow(y,2));
}
Should work after that.

e) Is also pretty straightforward. Think about returning a string this time.

3. Aug 10, 2013

### HallsofIvy

Staff Emeritus
Personally, I wouldn't use "Math.pow" to find a square: just use x*x. Also, I see not reason for the "double" in front of x and y if you have already declared them to be double. But the main thing I do not understand is your use of "double mag" as a parameter for the magnitude function. Rather, return it as a value:

Double magnitude() {
return Math.sqrt(this.x*this.x+ this.y*this.y);
}

Personally, I wouldn't use "this" as you have. You are working in "complex" so those should be understood. Of course, that means that you should not use "x" and "y" as parameters in a constructor: I would have said
Complex(){
//default constructor
x= 0.0;
y= 0.0;
}
and
Complex(Double u, Double v){
x= u; y= v; }

If your compiler really allows you to say ' this.x= "" ' when you have declared x and y as "Double", okay but that seems very strange to me!

4. Aug 10, 2013

### Borg

I see that other have also answered but I will leave this as I wrote it even though it duplicates the other posts in places.

Your example has several errors and does not compile. One of the main problems is that you do not seem to understand what "this" is used for. It is a reference to the instance of the class object and is usually only necessary when you need to distinguish between a class level variable and a method level variable that have the same name - like the case for the Complex(double x, double y) constructor. Otherwise, using this.x or this.y throughout the code is overkill. Similarly, this.Math and [STRIKE]this.mag[/STRIKE] doesn't work. They are not class level variables.

Do not pass in the variable type when calling a method. I.E. Math.pow(double x,2) should just be Math.pow(x, 2). If x started as a float and you were trying to cast it to a double, you would write Math.pow( (double)x, 2). But, it's not necessary to cast it in this case because it's already a double.

As for your method to calculate the magnitude, you are passing in a magnitude [STRIKE]and then immeadiately overwriting the value with a calculation using the class level variables of x and y[/STRIKE] that isn't used. What would be the purpose of passing in a variable into a method that isn't used for anything?

If a method is desired to calculate a result, it's usually desirable to return the result. The method should return the values that you're calculating. It would also be less confusing to name the method something like getMagnitude.

EDIT: Didn't see the declaration for mag right above the method.

Last edited: Aug 10, 2013
5. Aug 10, 2013

### Borg

Another note. You should get in the habit of declaring the accessibility of your variables and methods as public, private, protected, etc. By not declaring them, you allow access to them from other classes and can accidently modify data from outside of the class. This can make for some really painful debugging when you have another class accidentally modifying a variable because you didn't make it private. Similarly, there are times when you only want to call a method from within your class because it may be performing intermediate calculations for you.

6. Aug 11, 2013

### CAF123

Many thanks for your responses. I have followed your advice and put in changes to the code in the OP:
Code (Text):

public class Complex {

double x;
double y; //instance variables for the complex number

public Complex() {
x = 0;
y = 0; //default number
}

public Complex(double x_, double y_) {
x = x_;
y = y_; //constructor to initialise these variables

}

public double getX() {
return x; //getter method for x, the real component of the complex number
}
public double getY() {
return y; //getter method for y, the imaginary part of the complex number.
}

public double getMagnitude() {
return Math.sqrt(Math.pow(x,2) + Math.pow(y,2)); //method to compute magnitude of number
}

public String convertx() {
return String.valueOf(x);
}
public String converty() {
return String.valueOf(y);
}
public static double sum(Complex c1, Complex c2) {
double x1 = c1.getX() + c2.getX();
double x2 = c1.getY() + c2.getY();
}
public String convertx1() {
return  String.valueOf(x1);
}
public String convertx2() {
return  String.valueOf(x2);
}

}
When I compile, x1 (and x2) is not being recognized when I convert it to a string. I have defined what x1 is in the previous method, so why is this?

7. Aug 11, 2013

### Borg

You are defining x1 and x2 in the sum method. They are only accessible within that method.

8. Aug 11, 2013

### CAF123

This had crossed my mind, but the method was made public, so shouldn't I be able to access it throughout the class?

How should I convert the double to string then? I think I need to make two separate methods to return x1 and x2. I tried something like this before:
Code (Text):

public static String sum(Complex c1, Complex c2) {
double x1 = ..;
double x2 = ..;

return String.valueOf(x1);
return String.valueOf(x2);
When I compiled, however, the second return statement was 'unreachable'.

9. Aug 11, 2013

### Borg

Making the method public makes the method available to other classes. Variables that are defined within the method only exist within the method and are not available to other methods within the class.
The return instructs the code to leave the method and return to the code that called it. You can have multiple returns within a method but only if they are within things like if statements where there is a possibility of reaching one or the other return.

For your sum method, why do you think that it needs two Complex class values passed in? For what you want, delete c1 and c2, create a new variable within the method to get the sum and then return the String value of that.

10. Aug 11, 2013

### Borg

What point are you at in your Java class? You are clearly having difficulty with what is available and where it's available. I could put together some examples that might help but I don't want to cover more than you've been taught yet. Have you covered class inheritance? How about public, private, protected and/or abstract?

11. Aug 11, 2013

### CAF123

I thought I needed two instances of the class so that I could then find their sum.

I am having difficulty here because the sum is not a double, it is another complex number. If I delete the c1 and c2, I believe I should also delete 'static' from the method too?

12. Aug 11, 2013

### CAF123

I have heard of class inheritance, public, private. I am happy with the procedural programming but the object oriented side I am having some difficulty with.

My notes are somewhat vague and what I don't get is that there have been things said in this thread which contradict what it says in my notes. If you would be happy to put together some examples, that would be great. Alternatively, if you have any recommendations for good JAVA introductory textbooks that I could look into, that would also be great.

Thanks.

13. Aug 11, 2013

### Borg

I have to leave for now but will try to put something together this afternoon. Hopefully some others can help in the meantime.

14. Aug 11, 2013

### Zondrina

You're over complicating things a bit for part e). It's literally a one liner, but look closely at this and try to see what I'm doing :

Code (Text):
private String getXY() {
return "{" + x + ", " + y + "}";
}
So whenever you create a complex number, lets call it $c$ for now, you can call System.out.println(c.getXY()); which will return your desired {x,y} pairs. There's no need to convert the doubles to strings in this case because they can still be concatenated with strings and returned regardless.

So up until e) you should know how to return a double and return a string. For f) and g) though you have to be a bit more clever. I'll walk you through f) since you seem to be having a bit of trouble grasping the syntax, but you should be able to do g) on your own afterwards.

Notice f) asks you to return a Complex object, not a double. How do you do this you might ask? The exact same way you returned doubles and strings from before, that's how. Observe this code :

Code (Text):
private static Complex sum(Complex z1, Complex z2) {
return new Complex(z1.getX() + z2.getX(), z1.getY() + z2.getY());
}
This method returns a new complex object for you to use. Notice how it makes use of a constructor as well as two of the other methods that have been written. Also notice the private and static modifiers that have been added. Private insures protection from modifications by other classes and static allows you to reference your methods in a static fashion from anywhere in your code in any class.

Here's what your code should look like up until now, I also added a public main so you can observe some test cases and tinker with it to help your understanding :

Code (Text):
import java.lang.Math;

public class Complex {
private double x;
private double y;

//Public constructors
public Complex() {
x = 0;
y = 0;
}

public Complex(double _x, double _y) {
x = _x;
y = _y;
}

//Getters & setters
private double getX() { return x; }
private double getY() { return y; }

private double magnitude() {
return Math.sqrt(x*x + y*y);
}

private String getXY() {
return "{" + x + ", " + y + "}";
}

private static Complex sum(Complex z1, Complex z2) {
return new Complex(z1.getX() + z2.getX(), z1.getY() + z2.getY());
}

public static void main(String[] args) {
Complex z = new Complex(3,4);
Complex w = new Complex(2,1);

System.out.println(z.magnitude());
System.out.println(w.magnitude());

System.out.println(z.getXY());
System.out.println(w.getXY());

System.out.println(sum(z,w).getXY());
}

}

Look over that for awhile and try to follow what the code is doing as it is doing it. Then try part g) and show me what you get.

Last edited: Aug 11, 2013
15. Aug 11, 2013

### Borg

OK, here you go. I want to get to some basics and then expand from there as you understand things better. In the following example, I've created two constructors. One takes no variables and the other takes two. Build this, run it and see if you can understand what's going on. I've put lots of comments in to guide you along.

Code (Text):
public class MyClassExample {

// These are class-level variables and can be directly accessed
// anywhere within the class (except the main method).
private int x = 2;
private int y = 1;
private int z;

public MyClassExample(){
// Nothing is set, so the default values are used
// Note that z will be 0 even though it wasn't set.
// This normally only happens for a few primitive types.
}

public MyClassExample(int x, int y){
this.x = x; // The incoming variable x is being used to set the class level variable x
this.y = y; // The incoming variable y is being used to set the class level variable y
z = x + y;  // For this class, if only x and y are supplied, then z is set to x + y
}

public String getAllClassLevelVariables(){
// The only things that you can access here are class-level variables.
return "X: " + x + ", Y: " + y + ", Z: " + z;
// You can't access whosOnFirst, whatsOnSecond, example1 or example2 from this method.
}

public static void main(String... args) {
// Create three instances of MyClassExample
MyClassExample example1 = new MyClassExample();

// Examine what you have as you go
System.out.println("Example 1 variables are X: " + example1.x + ", Y: " + example1.y + ", Z: " + example1.z);

// This is about as confusing as I can make it but the point is to see that
// the variable names that are sent to a class or method don't have to be the same.
int whosOnFirst = 5;
int whatsOnSecond = 10;
// Create a MyClassExample(int x, int y) instance
// whosOnFirst becomes x (not this.x) and
// whatsOnSecond becomes y (not this.y)
// when you get to the constructor.
MyClassExample example2 = new MyClassExample(whosOnFirst, whatsOnSecond);

// This print statement does the same thing as the print statement above for the example 1 instance
// Why bother?  Think about how painful it would be to create the print statement
// if there were 100 variables to print out.  The method allows you to write it once
// for any instance of the class.
System.out.println("Example 2 variables are " + example2.getAllClassLevelVariables());
}
}
And always remember, print statements are your friend.

16. Aug 11, 2013

### CAF123

The code for g) in the class would be:
Code (Text):

private static Complex multiply(Complex z1, Complex z2) {
return new Complex(z1.getX()*z2.getX() - z1.getY()*z2.getY(), z1.getX()*z2.getY() + z1.getY()*z2.getX());
}
I have compiled the code and it runs fine. I have a question though:
Why do we need to include a default constructor?

Many thanks.

Last edited: Aug 11, 2013
17. Aug 11, 2013

### Borg

I'm not trying to duplicate your assignment. I'm showing you different constructors so that you get a feel for how things work. For your assignment, you are correct that you don't need a default constructor.

So, do you understand how the variables are being handled in the example?

BTW, what you're doing with the static solution for g is not going to work.

18. Aug 11, 2013

### CAF123

Sorry, that post was directed at Zondrina. Why would you need a default constructor at all?

I have some questions, but I will ask tomorrow - it is getting late here.

I have edited 'complex' to 'Complex', thanks.

19. Aug 11, 2013

### Borg

I saw that but, for some reason I was thinking that it was worse than that. My bad - changing it to Complex was all that was needed.
I'm on the U.S. East Coast but I get up very early. We can start again whenever you're ready.

Last edited: Aug 12, 2013
20. Aug 11, 2013

### Zondrina

It's a convention to include the default constructor whether or not it will be needed. It makes it easier for other programmers to use your code which is vital in the industry. Simplifying accessibility in code when you work on teams of programmers is really important since other people on your team will be working on different classes than yours.

The problem with that is they might not know your code inside and out, but the power of the dot operator '.' makes it so it doesn't matter if you assign values to your objects or not through parameters when you create it. They will be able to create a quick instance of your object and assign values to it when necessary ( Presuming a decent IDE is being used... like eclipse ).

Good job with part g) :).

Last edited: Aug 11, 2013