import java.io.*; public class FactorialMain { public static void main (String[ ] args) { final int MAX = 20; // because 21! > Long.MAX_VALUE final int SENTINEL = -1; final String PROMPT = "\nPlease enter a non-negative integer (at most " + MAX + "), or " + SENTINEL + " to quit: "; final String ERROR = "Error: the input must be a non-negative integer or " + SENTINEL; final String MESSAGE = " factorial is "; BufferedReader reader = new BufferedReader (new InputStreamReader (System.in)); int n; while (true) { try { System.out.print (PROMPT); n = Integer.parseInt (reader.readLine()); if (n == SENTINEL) break; if (n > MAX) throw new IllegalArgumentException(); System.out.println (n + MESSAGE + factorial (n)); } // try catch (Exception e) { System.out.println (e); } // catch } // while } // method main /** * Calculates the factorial of a non-negative integer, that is, the product of all * integers between 1 and the given integer, inclusive. The worstTime(n) is O(n), * where n is the given integer. * * @param n the non-negative integer whose factorial is calculated. * * @return the factorial of n * * @throws IllegalArgumentException if n is less than 0. * */ public static long factorial (int n) { if (n < 0) throw new IllegalArgumentException( ); if (n <= 1) return 1; return n * factorial (n - 1); } // method factorial } // class FactorialMain