Reputation:
For printing the value of factorial, I want to use the value of fact in the facto() function. How can I achieve this?
I have tried declaring variables i and fact in the facto() function.
public class Factorial {
int fact=1;
int n=5,i=1;
void facto()
{
for(i=n;i>=1;i--)
{
fact=fact*i;
}
}
public static void main(String args[])
{
Factorial obj1= new Factorial();
System.out.println(obj1.fact);
}
}
The answer I'm getting is what it gets the value from the class and is initialized with 1. I want to get 120 as the solution.
Upvotes: 0
Views: 63
Reputation: 346
Void function means the function that does not return any value, so it is wrong to use void function.
If you want to get a value from the method. You should use a method that can return a value as following :
public class Factorial {
public int facto()
{
int fact=1;
int n=5,i=1;
for(i=n;i>=1;i--)
{
fact=fact*i;
}
return fact;
}
public static void main(String args[])
{
Factorial obj1= new Factorial();
System.out.println(obj1.facto());
}
}
ps : I have changed the place of variables to scope of facto() method with warning of @Idle_Mind. Because this has a slight side effect in that if you call facto() more than once you'll get different results. To "fix" this you could re-initialize "fact" to 1 inside facto()
Upvotes: 1
Reputation: 159270
Don't use fields. Use a parameter and a return value.
public class Factorial {
private int facto(int n) {
int fact = 1;
for (int i = n; i >= 1; i--) {
fact = fact * i;
}
return fact;
}
public static void main(String args[]) {
Factorial obj1 = new Factorial();
System.out.println(obj1.facto(5));
}
}
Upvotes: 1