Thread: how to use a variable of one method in another method

1. Member Join Date
Oct 2008
Posts
2
Rep Power
0 how to use a variable of one method in another method

Hello! I'm an engineering student, still beggining my JAVA studies...
i've got the flollowing doubt:

when i want to use a method (met2) inside another method (met1), i must use class.met2(variable), right?

what happens is:
in the method met2, i've got a loop (recursion), in which the value of the variable "a" varies in each recursive cycle.
i wanna use the current value of "a" in the method met1....

so I tried to put:

int u= a.met2

or

int u=met2.a

and i doesn't work..

if i just use "a" in the method met1, the compiler - eclipse - claims, naturally: "a cannot be solved"...

will anyone gimme some help?

thanks a lot!

Lucas.
_________________ 2. i(t) doesn't work..
What doesn't work? Do you get an error message? Post it here with the code.

If the variable a is local to a method, then you can not access it from another method. a needs to be a class variable to be accessible to other methods and classes.
You can pass the value of a to another method by using it as a parameter:

public void method1() {
int a = ...;
...
method2(a); // pass a to method2
} // end method1() 3. Member Join Date
Oct 2008
Posts
2
Rep Power
0 public static int sumDivr (int x, int xInicial) {
if (x==0)
return 0;

else if (xInicial%x==0 && x!=xInicial)
return x + sumDivr (x-1,xInicial);

else
return 0 + sumDivr (x-1,xInicial);

}

public static int sumDoisAmig (int f, int g) {
return (sumDivr(f,f)==g && sumDivr(g,g)==f && f!=g) ? (f+g) : 0 ;
}

public static int sumAmigosr (int n, int b) {

int u=a.sumFinalr; /* i want the variable "u" to have the value that the variable "a", of the method "sumFinalr", has at the current instant*/

if (b==n) return 0;

else return sumDoisAmig (u,b) + sumAmigosr (n,b+1);

}

public static int sumFinalr (int n, int a) {

if (a==n) return 0;

else return sumAmigosr(n,a) + sumFinalr(n,a+1) ; 4. I think you should study more about methods and return values from a method. 5. the value that the variable "a", of the method "sumFinalr" has at the current instant
The only way would be for the method sumFinalr to use that value in its call to another method. In sumFinalr it could pass the value of a to another method as a parameter:
sumAmigosr(a,...);// pass the value of a to sumAmigosr  Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•