Karl
Karl

Reputation: 97

Java How to chain with Math class

I am at the very basics of learning Java, I have tried searching for this answer but maybe I do not know what I am searching for. I want to perform multiple operations on a number, so far the only way I know how to do that is the have intermediate variables with operations performed one at a time. This can't be the best way. The following is code in my main method that I would love to have work:

  double sqrtAbsInput = promptForDouble("I can get the square root of the absolute value.");
  double sqrtAbsOutput = sqrtAbsInput.Math.abs().sqrt();
  System.out.println(sqrAbsOutput);

promptForDouble() method returns a double, it is the second line that concerns me most. The error I get is

"error: double cannot be dereferenced."

I assume what's going on is the variable needs to be the argument of the Math class methods, but I understand it could also have to do with the variable being a primitive type.

Upvotes: 0

Views: 326

Answers (3)

user4413257
user4413257

Reputation:

Math class does not implement "builder pattern" (for efficiency reasons), but you can create your own Math class implementation which allows chaining.

Here is an example:

public class MathBuilder {
    private double value;

    public MathBuilder(double value) {
        this.value = value;
    }

    public MathBuilder abs() {
        value = Math.abs(value);
        return this;
    }

    public MathBuilder sqrt() {
        value = Math.sqrt(value);
        return this;
    }

    // other builder-math methods...

    public double build() {
        return value;
    }
}

Usage:

double result = new MathBuilder(-10).abs().sqrt().build();

Or with Java 8:

public class MathBuilder {
    private double value;

    public MathBuilder(double value) {
        this.value = value;
    }

    public MathBuilder apply(DoubleUnaryOperator o) {
        value = o.applyAsDouble(value);
        return this;
    }

    public double build() {
        return value;
    }
}

Usage:

double result = new MathBuilder(-10)
        .apply(Math::abs)
        .apply(Math::sqrt)
        .build();

Upvotes: 2

Mureinik
Mureinik

Reputation: 311938

abs and sqrt aren't methods of double (which is a primitive, so it doesn't have any methods anyway - as noted in the error message you're getting), but static method of Math that take a double as an argument and return a double result:

double sqrtAbsOutput = Math.sqrt(Math.abs(sqrtAbsInput));

Upvotes: 3

rodrigoap
rodrigoap

Reputation: 7480

You will have to do this:

System.out.println(Math.sqrt(Math.abs(sqrtAbsInput)));

Upvotes: 1

Related Questions