Home > database >  How do I make a method like int.getRed() in java?
How do I make a method like int.getRed() in java?

Time:02-12

I am making an imaginary number graphing calculator with java (using a bi={a,b}) and want to make new functions for - * / and ^ operators, since they don't work on double[] variables. I know how to make normal methods, like File(), but I am having trouble doing things like int.getRed(). Here's my code for the addition method

private static double[] CPlusC(double[] a, double[] b) {
    double aN = a[1]   b[1];
    double bN = a[2]   b[2];
    double[] ansN = {aN,bN};
    return ansN;
}

I have the addition parts correct, I just can't find anything to make the function more "realistic", as in double[].CPlusC(double[]) Could someone please help me out? Once I figure this one out, I should know how to do the others. Thank you so much!

CodePudding user response:

As I mentioned in my comment, you can't create extension methods like you would do in Kotlin or C#.

But you shouldn't use double[] to handle complex numbers in the first place. A better approach would be to create your own Complex class that contains all necessary methods you need for calculation.

Your class could look like this:

public class Complex {
    private final double re;
    private final double im;

    public Complex(double re, double im) {
        this.re = re;
        this.im = im;
    }

    // getters and other methods

    public Complex add(Complex other) {
        double addedRe = re   other.re;
        double addedIm = im   other.im;
        return new Complex(addedRe, addedIm);
    }

    public String toString() {
        return String.format("%s %s %si", re, im < 0 ? "-" : " ", Math.abs(im));
    }
}

Then you can do your calculations like:

Complex c1 = new Complex(0, 1);
Complex c2 = new Complex(2.5, 1.3);
Complex c3 = c1.add(c2);
System.out.println(c3) // 2.5   2.3i
  • Related