Soluzione 4.6

La classe FactorGenerator.
public class FactorGenerator
{
  public FactorGenerator(int anIntValue)
  {
    if (anIntValue <= 1)
      throw new IllegalArgumentException();
    currentValue = anIntValue;
    currentFactor = 2;
  }

  public int nextFactor()
  {
    if (!hasMoreFactors())
        throw new IllegalStateException();  
    for (int i = currentFactor; i <= currentValue; i++)
        if (currentValue % i == 0)
        {
            currentFactor = i;
            currentValue = currentValue / currentFactor;
            return i;
        }
    return -1; // non succede mai, ma il compilatore lo vuole... perche`?
  }

  public boolean hasMoreFactors()
  {
      return currentValue != 1;
      /* 
        ... che e` equivalente a:
        if (currentValue !=1)
            return true;
        return false;
      */
  }

  private int currentValue;
  private int currentFactor;
}
La classe di collaudo FactorGeneratorTester. Porre attenzione a come abbiamo gestito le eccezioni.
import java.util.Scanner;

public class FactorGeneratorTester
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        boolean done = false;
        while (!done)
        {
            System.out.println("Inserire intero positivo (Q per uscire)");
            String input = in.nextLine();
            if (input.equalsIgnoreCase("Q"))
                done = true;
            else
            {
                try
                {
                int anIntValue = Integer.parseInt(input);
                FactorGenerator generator = new FactorGenerator(anIntValue);
                int i = 1;
                while (generator.hasMoreFactors())
                  {  
                    System.out.println("Fattore " + i + ": " +
                                        generator.nextFactor());
                    i++;
                  }
                }
                catch (NumberFormatException e)
                {  System.out.println("non e` un int");
                   System.out.println(e); }
                catch (IllegalArgumentException e)
                {  System.out.println("non e` un intero >1");
                   System.out.println(e); }
                catch (IllegalStateException e)
                {   System.out.println("sono finiti i fattori!");
                    System.out.println(e);}
            }
        }
    }
}