The code below is working fine but I'm wondering if there are any issues coming in object creation time.
import java.util.Scanner;
public class FactorialExample {
public FactorialExample(int n) {
int fact=1;
for(int i=1;i<=n;i++) {
fact=fact*i;
}
System.out.println("the factorial of a given number is::"+fact);
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter any Integer Value:");
int value=sc.nextInt();
FactorialExample fe=new FactorialExample(value);
}
}
Yes, you're onto the right assumption - don't use business logic in the constructor.
At most, initialize the object state.
Otherwise, things like exception handling, testing and mocking can becoming difficult.
In your code, you can completely avoid having a constructor, in fact:
import java.util.Scanner;
public class FactorialExample {
int solve(int n){
int fact=1;
for(int i=1;i<=n;i++){
fact=fact*i;
}
return fact;
}
public static void main(String[] args) {
FactorialExample fe=new FactorialExample();
Scanner sc=new Scanner(System.in);
System.out.println("Enter any Integer Value:");
int value=sc.nextInt();
int solution = fe.solve(value);
System.out.println("tha factorail of a given number is::"+solution);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With