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;
}
我的代码工作正常但是如果我输入11,它会显示无效消息,它还会计算11我不想要的阶乘。
答案 0 :(得分:2)
您应该移动检查用户输入范围的代码,使其高于对factorial()
函数的调用:
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);
}
}
请注意,对factorial()
和println()
语句的调用现在都在新的else
块内。因此,如果用户输入的数字无效,则程序给出的唯一响应是错误消息。
如果您还希望在factorial()
中进行错误检查,最明确的方法可能是在给出无效输入时抛出IllegalArgumentException
:
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....
}