0

I want to use result and power in another method in this class.How it can be possible?

private double facto(int n) {
    for (int i = 1; i <= n; i++) {
        result = result * i;
    }
    return result;
}

private double power(int x,int n) {
    double power = Math.pow(-1, n) * Math.pow(x, 2 * n);
    return power;
}
1
  • 1
    Call the methods and assign the value returned to a variable and use it. You will find out all about this in pretty much any introductory chapter on Java methods. Commented Mar 2, 2016 at 22:18

2 Answers 2

1

You simply call the methods from within the other method.

private void example(){
    System.out.println("facto - " + facto(1));
    System.out.println("power - " + power(1,1));
}

That example will simply output the return values. If you want to set the return value to a variable, do this.

private void example(){
    double ex1 = facto(1);
    double ex2 = power(1,1);
    //Now ex1 holds the return value of facto(), and ex2 holds the return value of power().
}

Also, you should instantiate the result int within the facto() method or else it won't work. If you have it instantiated elsewhere, it will be an issue relating to the scope of the variable. I am not sure how familiar you are with this, so as a side note: The result variable will always be 0 when you first call the method due to the local scope.

private double facto(int n) {
    int result = 0;
    for (int i = 1; i <= n; i++) {
        result = result * i;
    }
    return result;
}
Sign up to request clarification or add additional context in comments.

Comments

0

There are multiple possibilities:

  1. You can call your method within another method:

    public void othermethod(){

       double power = power(x,n);
        double facto = facto(n);
    

    }

  2. You can create class variables:

    private double power = null; private double facto = null;

Now within your methods you set them (for this of course the methods need to run):

 private double facto(int n) { 
        double result;
        for (int i = 1; i <= n; i++) { 
               result = result * i; 
        } 
        this.facto = result;
        return result; 
  } 

  private double power(int x,int n) {      
         double power = Math.pow(-1, n) * Math.pow(x, 2 * n); 
         this.power = power ;
         return power; 
   }

The this indecates to use the class variable in case that you have a method variable with the same name.

Sorry I am on mobile, so could not get all formated well

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.