java - 如何让它运行直到用户输入 0 或负数?
问题描述
我很想知道如何让它运行直到用户输入 0,我尝试做 while (i <=number) && (number != 0) 但它没有用。
import java.util.Scanner;
public class Factorial {
private static Scanner sc;
public static void main(String args[]){
int i =1, factorial=1, number;
System.out.println("Enter the number to which you need to find the factorial:");
sc = new Scanner(System.in);
number = sc.nextInt();
while (i <=number) {
factorial = factorial * i;
i++;
}
System.out.println("Factorial of the given number is:: "+factorial);
}
}
解决方案
将 number 初始化为非零整数并将所有内容包含在 while 循环中。
public class Main {
private static Scanner sc;
public static void main(String args[]){
int number = 7; // can just use a random starting number which is not 0
while (number != 0) { // Add a while loop to make it keep asking for factorials until 0 is given to quit
int i = 1, factorial = 1;
System.out.println("Enter the number to which you need to find the factorial or enter 0 to quit:");
sc = new Scanner(System.in);
number = sc.nextInt();
while (i <= number) {
factorial = factorial * i;
i++;
}
System.out.println("Factorial of the given number is:: " + factorial);
}
System.out.println("Thanks for using the factorial calculator. ");
}
}
推荐阅读
- asp.net-mvc - 如何减去两个日期并以分钟为单位转换新日期?
- javascript - 如何更改嵌套/递归 JSON 的结构
- flutter - 如何在颤振中改变状态?
- xpath - xpath:获取数据属性/值
- html - 你能避免限制可滚动容器的背景颜色吗?
- css - 带有背景 GIF 的透明文本在 Chrome 移动版 79.0.3945.73 React 上不起作用
- apache-spark - 无法访问 Apache Spark 中的文件,这是 Spark 的全新版本,用于大学独立学习
- flutter - Flutter 使用 GlobalKey 从另一个类更改状态
- javascript - 将两个数组组合成对
- swift - List (SwiftUI) 中的 HStack 数量是否有限制?