public static void main (String args []) {
Scanner sc = new Scanner(System.in);
int number;
int factor=1;
System.out.println("Enter a number to find the factorial of it: ");
number= sc.nextInt();
factor=factorial(number);
if (number < 1 || number > 10)
{
System.out.println("Invalid!! the number has to be between 1 and 10");
}
System.out.println("The factorial of "+number+" is = " +factor);
}
public static int factorial (int number) {
int result = 1;
if (number < 1 || number > 10)
{
System.out.println("Invalid!! the number has to be between 1 and 10");
}
else {
for(int x=1; x<=number; x++ ) {
result= result*x;
}
}
return result;
}
My code works fine but if I input 11, it says invalid message and it also calculates the factorial for 11 which I don't want.
You should move the code that checks the range of the user input so that it's above the call to the factorial()
function:
public static void main (String args []) {
Scanner sc = new Scanner(System.in);
int number;
int factor=1;
System.out.println("Enter a number to find the factorial of it: ");
number= sc.nextInt();
if (number < 1 || number > 10) {
System.out.println("Invalid!! the number has to be between 1 and 10");
} else {
factor=factorial(number);
System.out.println("The factorial of "+number+" is = " +factor);
}
}
Note that the call to factorial()
and the println()
statement are both inside the new else
block now. Thus, if the user enters an invalid number, the only response given by the program is the error message.
If you also want error checking in factorial()
, the clearest way to do that would probably be to throw a IllegalArgumentException
when an invalid input is given:
public static int factorial (int number) {
int result = 1;
if (number < 1 || number > 10)
{
System.out.println("Invalid!! the number has to be between 1 and 10");
throw new IllegalArgumentException("Factorial input has to be between 1 and 10");
}
// rest of your code....
}