0

I have written a method in one class and wish to call it in another, i.e print the result. Here is the method's class:

public class squareRoot {

    public double absoluteValue(double x){
        if (x < 0)
            x = -x;
        return(x);
    }

    public double squareRoot(double x){
        double epsilon  = .00001;
        double guess    = 1.0;

        while(absoluteValue(guess * guess - x) >= epsilon)
            guess = (x / guess + guess) / 2.0;
        return guess;
    }
}

The second class is a simple gui class and I wish to call the squareRoot method. I obtain the user input and then try to print the function, like this (with x being the user input in the gui class). However it is not working

 squareRoot(x);
2
  • Please give more details as to the manner in which it is not working. Are you getting an error, a wrong calculation, compilation error etc? Also please show how you are instantiating the squareRoot class and using it Commented May 12, 2016 at 7:58
  • @RobMcFeely I created an object of the squareRoot class, squareRoot obj; Commented May 12, 2016 at 8:00

2 Answers 2

3

Declare your method as static

public static double squareRoot(double x)

and then call it by

System.out.println(squareRoot.squareRoot(x));
Sign up to request clarification or add additional context in comments.

Comments

0

Be careful with static approaches, in more complex systems you'd have to think twice before declaring a static.

I recommend creating a instance for this purpose squareRoot sqr = new squareRoot();

You can then access the class method by e.g. sqr.squareRoot(int value)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.