import static java.lang.System.*;  // cf. Java 5 ...

// Pour les entrees-sorties
import java.io.*;
/**
  * <p>Titre :  FactRexI.java - Calcul récursif de factorielle </p>
 * <p>Description :  Gestion d'exceptions via 'try', 'catch' et 'finally'</p>
 * <p>Copyright :  (c) ~/2a env.  ESSTIN </p>
 * @author  (c)~/2A env. H. Nguyen-Phu
 * @version 1.1   05.04.2008
 * @since    1.0   11.15.2002
 * @see       facrec   
 */
 
public class FactRexI  {
  
  public static int factorielle(int n) throws ErreurFactorielle, ErreurDepassement  {
    if (n < 0) throw new ErreurFactorielle();
    if (n >= 13) throw new ErreurDepassement();
    int fact = 1;	  // Resultat
	if (n > 1)
		  fact = n * factorielle(n - 1);
	return fact;
  }

  public static void main(String arg[])  {
    int nombre = 0;  // Nombre dont on calcule la factorielle
    out.println("\nFactRexI: Calcul de n! via 'int' --- MAJ: 19h10 05.04.2008 (c)~/2A env.");
    out.println("--------  Version récursive avec captures d'exceptions et 'finally'\n");
	try  {
      // Pour les saisies via le clavier avec gestion des exceptions d'E/S 
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      // Saisie du nombre
      out.print("Donner un nombre entier positif ou nul : ");
      nombre = Integer.parseInt(in.readLine());
      out.println("La factorielle de ce nombre est: \t"+ nombre +"! = " + factorielle(nombre));
    }
     // Traitement  des différentes exceptions éventuelles  :
    catch (ErreurFactorielle eF) {
       out.println(eF.msg);  }
	catch (ErreurDepassement eD) {
       out.println(eD.message);  }
    catch (NumberFormatException nfe) {
	   out.println(nfe.toString());   }
    catch (Exception e)  {  // autre  exception ...
	   out.println(e.getMessage());
	   out.println(e.toString()); 	}
	finally  {
	   out.println("\nEXERCICE (à faire): 'Finally', pour calculer au delà de 12!, ré-écrire ce programme avec des types 'long', 'float' ou 'double' ...");
	}
	es.attente();
  }     
}  

// Exception generee pour le cas des  valeurs négatives
class ErreurFactorielle extends Exception {
  public String msg;
  public ErreurFactorielle()  {
    msg = "ERREUR : FACTORIELLE NON DEFINIE pour n < 0 !";   }
}

// Exception generee s'il y a dépassement de la capacité des entiers 'int' 
class ErreurDepassement extends Exception {
  public String message;
  public ErreurDepassement()  {
    message = "ERREUR : DEPASSEMENT DE CAPACITE DES entiers 'int' pour n >= 13 !";  }
}

