简体   繁体   English

如何使其运行直到用户输入0或负数?

[英]How can to make it run until user enters 0 or negative number?

I would love to know how to make it run until user enters 0, i tried doing while (i <=number) && (number != 0) but it didnot work. 我很想知道如何让它运行直到用户输入0,我尝试在(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);
    }
}

Initialize number to a non-zero integer and enclose everything in a while loop. 将数字初始化为非零整数,并将所有内容封装在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. ");

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 斜边程序,直到用户输入2才弄清楚如何让程序运行 - Hypotenuse program, can't figure out how to let program run until user enters 2 Java 代码添加 do while 循环以使其运行直到用户输入 0 - Java code adding do while loop to make it run until user enters 0 如何重复直到用户输入整数? - How to repeat until the user enters an integer? 如何让用户输入进入for循环并使程序循环直到用户输入退出 - How to get user input into a for loop and make the program loop until user enters quit 在用户在Java中输入空白行之前,我将如何进行此循环? - How would I make this loop until the user enters a blank line in java? 使程序“暂停”,直到用户在JTextField中输入内容为止 - Make program “pause” until the user enters something in a JTextField 用户输入负值时如何退出程序-Java - How to exit the program when a user enters a negative value - Java 如何使用用户在输入框中输入的数字的平方根,而不是数字本身? - How can I use the square root of a number that the user enters in an input box, instead of the number itself? 在用户输入-1之前,如何循环这段代码? - How do I loop this code until the user enters -1? 如何在用户输入完成之前继续输入字符串 - How to keep entering a string until user enters done
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM