//  Scott DeRuiter        7/16/02
//  Factorial.java
//  Use recursion to calculate a factorial.
//  7/20/2011 - Greenstein: Changed TextReader to Scanner

import java.util.Scanner;

class Factorial     
{ 
	private int input;
	private long result;

	public Factorial ( )
  	{
		input = 0;
		result = 0;
	}

	public static void main ( String [] args )  
  	{	
		Factorial f = new Factorial ( );
		f.GetPositiveInt ( );
		f.FindAndPrint ( );
	}

	public void GetPositiveInt ( )   
  	{
		Scanner console = new Scanner ( System.in );
		do    
      	{
			System.out.print ( "\n\nEnter an int (0 to 20) -> " );
			input = console.nextInt ( );
		} while ( input < 0 || input > 20 );
	}

	public void FindAndPrint ( )   
 	{
		result = fact ( input );
		System.out.println ( "\n\n   " + input + "! = " + result );
	}

	public long fact ( int n )    
  	{
		System.out.println ( n );
		if (1 == n || 0 == n)
			return 1;
		else
			return (n * fact(n - 1));
	}
}

Back to Lesson 13 Examples

Back to Java Main Page