我需要修改此代码,以便在输入负数时显示错误消息。我知道,其他陈述必须适合我才可以弄清楚哪里。
答案 0 :(得分:1)
我想您所要做的就是检查输入是否不正确以引发异常。
public static void numberFactorial() {
System.out.println("Option 2 selected, enter a number: ");
int number = sc.nextInt();
if(number < 0){
throw new IllegalArgumentException()
}
// ... rest of the code
}
答案 1 :(得分:0)
public static void numberFactorial() {
System.out.println("Option 2 selected, enter a number: ");
int number = sc.nextInt();
// here you can check for negative number
if(number >= 0){
System.out.println("The factorial is: " + number + " ");
for (int i = 1; i <= number; i++)
{
factorial *= i;
if ((number - 1) > 0)
{
System.out.print("x" + (number - i) + " ");
}
System.out.println("=" + factorial);
}
}else{
System.out.println("Negative number is not allowed, entered number is: " + number + " ");
}
}
答案 2 :(得分:0)
这不是最好的方法,
public static void numberFactorial() {
System.out.println("Option 2 selected, enter a number: ");
boolean isNegative =true;
int number;
while (isNegative) {
number = sc.nextInt();
if(number < 0 ){
System.out.println("Negative Number Detected, please enter your number again");
}else {
break;
}
System.out.println("The factorial is: " + number + " ");
for (int i = 1; i <= number; i++)
{
factorial *= i;
if ((number - 1) > 0)
{
System.out.print("x" + (number - i) + " ");
}
System.out.println("=" + factorial);
}
}