Gaussian class in java

I am making a class that mimics a Gaussian integer. I use the constructor in my add method to add two two parts of gInt, and then return a new gInt, which is the sum. But for some reason, when I try to implement this method, Java says gInt is required when I initialize a new gInt and find a void. Why should it be? I included the class below and indicated which line is causing this error.

public class gInt {

    private int real;
    private int imag;



    public void gInt(int r)
    {
        imag=0;
        real=r;

    }

    public void gInt(int r, int i)
    {
        real=r;
        imag=i;

    }

    gInt add(gInt rhs)
    {
        gInt added;
        int nReal=this.real+rhs.real;
        int nImag=this.imag+rhs.real;

        added= gInt(nReal,nImag);   //--> Says it requires a gInt and found a void

        return added;
    }
}
+4
source share
3 answers

Use this implementation and everyone will be happy:

public class GInt {

    private int real;
    private int imag;

    public GInt(int r) {
        imag=0;
        real=r;
    }

    public GInt(int r, int i) {
        real = r;
        imag = i;
    }

    GInt add(GInt rhs) {
        GInt added;
        int nReal = this.real + rhs.real;
        int nImag = this.imag + rhs.real;

        added = new GInt(nReal, nImag);

        return added;
    }
}

Comments:

  • Do not use class names starting with a lowercase letter (e.g. gIntinstead gInt)
  • Java Java, void OP
  • new gInt Java
+1

. :

public gInt(int r)
{
    imag=0;
    real=r;

}

public gInt(int r, int i)
{
    real=r;
    imag=i;

}

, void .

, new:

added= new gInt(nReal,nImag);

, Java, .

+3

void added = new gInt(nReal,nImag); , , added = new gInt.gInt(nReal,nImag); gInt - , , !

0
source

All Articles