import java.io.*;
import javax.swing.JOptionPane;

/**
 *
 * <p>Titre :  facrec.java - Calcul récursif de factorielle </p>
 * <p>Description :  Gestion d'exceptions via 'Try', 'Catch' et 'Finally'</p>
 * <p>Copyright : Copyright (c) ~/2a env. ESSTIN </p>
 * @author  (c)~/2A env. H. Nguyen-Phu
 * @version 1.1   27.08.2006
 * @since   1.0   11.15.2002
 */

public class facrec  {

  static PrintWriter jo = new PrintWriter(System.out, true);

  public static void main(String args[]) throws IOException  {
    int  n = 0;
    long res=0;	  // res : résultat du calcul de fact(n)
    String titre = "Calcul du factoriel N par r\u00e9cursion";
    jo.println("facrec.java - "+titre+ " (c)~/2A env.");
    jo.println("------  Emploi: java  facrec  N (ou  N  à lire ...)   MAJ: 2006.08.27 18h25\n");
    int answer;
    do
      try  {
        if (args.length == 1)  {
         	n = Integer.parseInt(args[0]);
//              if (n < 0 || n > 20)     n = 20;
        }
        else  {
          String s = JOptionPane.showInputDialog(null, " n= ? ", titre,
                                                 JOptionPane.OK_CANCEL_OPTION);
          if (s != null) {
            n = Integer.parseInt(s);
            if (n < 0 || n > 20)
              throw new IllegalArgumentException (n+" en dehors des bornes:  0<= n <=20 !");
          }
         }
         res = fact(n);
         JOptionPane.showMessageDialog(null, "  "+ n + " ! =  " + res);
       }

      catch (NumberFormatException nfe)  {
        JOptionPane.showMessageDialog(null, nfe.getMessage() + " n'est pas un entier", titre, JOptionPane.ERROR_MESSAGE);
      }
      catch (IllegalArgumentException iae)  {
        JOptionPane.showMessageDialog(null, iae.getMessage(), titre, JOptionPane.ERROR_MESSAGE);
      }
      finally  {
        answer = JOptionPane.showConfirmDialog(null, "Voulez-vous quitter ?", titre, JOptionPane.YES_NO_OPTION);
      }
    while (answer == JOptionPane.NO_OPTION);

    es.attente();
    System.exit(0);

    }
    /**
     * 'fact': Méthode de classe pour calculer récursivement N! avec double cond. d'arrêt
     * @param N
     * @return un entier long
     */
  public static long fact(int N)  {
	long tmp;
        if (N < 0 || N > 20)
          throw new IllegalArgumentException(N+" invalide ! Merci de donner 0<= N <=20 !");
	switch(N)  {
		case 0: tmp = 1;  break;
		case 1: tmp = 1;  break;
		default: tmp =	N*fact(N-1);
	}
	return tmp;
  }
}

