【发布时间】:2023-03-04 04:51:01
【问题描述】:
所以我有这个接受用户输入的阶乘程序。一切正常,但我试图弄清楚如何通过输入 0 来结束程序。由于它是布尔运算,我无法输入 if 语句,因为我会得到一个编译错误。
import java.util.*;
import java.io.*;
public class Assignment2A {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
boolean correct = false;
while(!false){
try{
System.out.println("Welcome to the factorial function");
System.out.println("Please enter a number or press 0 to exit");
int n = scan.nextInt();
// if(n=0){
// System.exit(0);
//}
int factorial= fact(n);
System.out.println("The Factorial of the number entered is: " + factorial);
correct = true;
}catch(Exception e){
System.out.println("That is not a number!");
System.exit(0);
}
}
}
static int fact(int n){
int output;
if(n==1){
return 1;
}
output = fact(n-1)*n;
return output;
}
}
【问题讨论】:
-
while(!false){与while(true){相同 -
应该是
if (n == 0),而不是(n=0) -
仅供参考:这里不需要
System.exit的大锤 - 只需致电break。