简体   繁体   中英

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.

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.

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. ");

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM