import java.util.Scanner;
public class ex11
{
static Scanner type=new Scanner(System.in);
public static void main(String args[])
{
int fact=1;
System.out.println("Enter a natural number ");
int num=type.nextInt();
int i=1;
while(i<=num)
{
fact*=i;
i++;
}
System.out.println("Factorial of number " + num + " is " + fact);
}
}
我试图在 while 循环中放置一个条件语句。要测试的条件是,如果 num 是负数, S.O.P.("You entered a negative #");
换句话说,
if(num<0)
S.O.P.("You entered a negative #");
但是它不能正确打印。
原文由 Rudy 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果您检查循环内部,那么它将不起作用,它仍然会乘以
fact
。在开始 while 循环之前,您需要确保num
不是负数。另外在旁注中,您可能应该在使用完扫描仪后关闭它们。