-3

Here's my code:

public abstract class Function{
    public abstract double evaluate(double x);
    public double findRoot(double a, double b, double epsilon){
        if( (evaluate(a) > 0 && evaluate(b) > 0) || (evaluate(a) < 0 && evaluate(b) < 0)){
            System.out.println("There is no root between these two points.");
        }
        double x = (a+b)/2;
        if(Math.abs(a-x) < epsilon){
            return x;
        }
        else if((evaluate(x) < 0 && evaluate(a) < 0) || (evaluate(x) > 0 && evaluate(a) > 0)){
            return findRoot(x, b, epsilon);
        }
        else{
            return findRoot(a, x, epsilon);
        }
    }
    public static void main(String[] args){
        double testSinFunc = SinFunc.findRoot(3, 4, .01);
        double testCosFunc = CosFunc.findRoot(1, 2, .01);
        if(testSinFunc == 3.14){
            System.out.println("SinFunc.findRoot(3, 4, .01) returned 3.14. Test passed!");
        }
        if(testCosFunc == 1.57){
            System.out.println("CosFunc.findRoot(1, 2, .01) returned 1.57. Test passed!");
        }
    }
}

The compiler says :

non-static method findRoot(double, double, double) cannot be referenced from a static context

What would I do to fix this?

user2342558
  • 5,567
  • 5
  • 33
  • 54
coder_2
  • 31
  • 1
  • 3
  • The suggested link explain how to call a non static method from a static method, but here maybe logic to make the method static instead of instantiate a class object only for its invocation. – user2342558 Sep 18 '19 at 16:57
  • Coder_2, did you tried my solution? If it helped you please mark it as accepted – user2342558 Sep 19 '19 at 10:17

1 Answers1

1

You can't invoke a non-static method (public double findRoot) from a static context (public static void main).

Because of the work that the method must perform, it make sense to make it static:

public static double findRoot(...)

That error says that in a static context, in which the main method is, the compiler cannot access the non-static method because non-static methods live only inside an object.

user2342558
  • 5,567
  • 5
  • 33
  • 54