[Solved] Why is my compiler giving me these two errors in Java?


So I see two glaring errors, the first of which is what the compiler is telling you, namely that real and imaginary have not been declared anywhere. In Java, you cannot use a variable unless you have previously declared it. You probably want to have a real and imaginary component of your ComplexNumber, so you need to declare member variables for it appropriately.

e.g.

public class ComplexNumber {
    float real;
    float imaginary;
    ...

The second error is that you are trying to assign the values of real and imaginary to your parameter variables, instead of the other way around. When you do this, you are throwing away the data that is being passed in to your method instead of storing it:

public ComplexNumber(float a, float b){
    a = real;       // this overwrites the value of a instead of using it
    b = imaginary;  // this overwrites the value of b instead of using it
}

Generally, the convention in Java is to try to give your member variables informative names, and then in your constructors, getters and setters, use the same names with a this. prefix for the member variables to distinguish them from the parameters.

Most modern IDEs will automatically generate your code for you in this format.

e.g.

public class ComplexNumber {
    float real;
    float imaginary;

    public ComplexNumber(float real, float imaginary) {
        this.real = real;
        this.imaginary = imaginary;
    }
}

solved Why is my compiler giving me these two errors in Java?