// File: FactTest.java import javax.swing.JOptionPane; /** * A class to compute factorials */ class FactFinder { // instance var private int number ; // the number to compute factorial of /** * Constructs a FactFinder object * @param number the number to compute factorial of */ public FactFinder(int number) { this.number = number ; } /** * Computes the factorial of the number. * @return the factorial */ public int getFact() { // trivial cases if (number < 0) return 0 ; // fact fn not defined for negatives if (number == 0) return 1 ; // 0! defined as 1 // recursive call with reduced case FactFinder previous = new FactFinder(number - 1) ; int previousFact = previous.getFact() ; return previousFact * number ; } } public class FactTest { public static void main(String[] args) { String input = JOptionPane.showInputDialog ("Enter number to find factorial of") ; int number = Integer.parseInt(input) ; FactFinder f = new FactFinder(number) ; int fact = f.getFact() ; System.out.print(number + " factorial is " + fact) ; // print messages (nothing to do with recursion) if ( number < 0 ) // input was negative System.out.println(" (factorial not defined for negative numbers)") ; else if ( number >= 0 && fact <= 0 ) // checking for overflow System.out.println(" (overflow occurred)") ; else System.out.println() ; } } /* sample o/p from several runs: 5 factorial is 120 1 factorial is 1 0 factorial is 1 10 factorial is 3628800 -5 factorial is 0 (factorial not defined for negative numbers) 37 factorial is 0 (overflow occurred) */