簡體   English   中英

如何使其運行直到用戶輸入0或負數?

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

我很想知道如何讓它運行直到用戶輸入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);
    }
}

將數字初始化為非零整數,並將所有內容封裝在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM