views:

107

answers:

2

I know how to do it using simple recursion, but in order to complete this particular assignment I need to be able to accumulate on the stack and throw an exception that holds the answer in it.

So far I have:

public static int fibo(int index) {
    int sum = 0;
    try {
        fibo_aux(index, 1, 1);
    }
        catch (IntegerException me) {
    sum = me.getIntValue();
    }
    return sum;
}

fibo_aux is supposed to throw an IntegerException (which holds the value of the answer that is retireved via getIntValue) and accumulates the answer on the stack, but so far I can't figure it out. Can anyone help?

+1  A: 

I don't know what your implementations for fibo_aux and IntegerException look like, but the following two implementations work with your existing code (I don't think there's anything wrong with the code you posted, so I assume something is awry in either fibo_aux or IntegerException). Maybe you'll find this helpful.

public static void fibo_aux(int index, int a, int b) throws IntegerException
{
    if (--index > 0)
        fibo_aux(index, b, a + b);
    else
        throw new IntegerException(a + b);
}

An implementation for IntegerException:

public class IntegerException extends Exception
{

    private static final long serialVersionUID = -6795044518321782305L;

    private Integer intValue;

    public IntegerException(int i)
    {
        this.intValue = i;
    }

    public Integer getIntValue()
    {
        return intValue;
    }
}
Dolph
A: 

Here you go :

public class ExcFib {

/**
 * @param args
 */
public static void main(String[] args) {

    new ExcFib().fibo ( 10 );

}

class FiboException extends Throwable
{
    public int n;
    public FiboException(int n)
    {
        this.n = n;
    }       
    private static final long serialVersionUID = 1L;        
}

public void fibo(int idx) {
    try {
        fibo_aux(idx-1,1,1);
    } catch (FiboException e) {
        System.out.println ( "F(" + idx + ") = " + e.n   );
    }                               
}

private  void fibo_aux(int i, int j, int k) throws FiboException {
    if ( i < 1 ) 
    {
        throw new FiboException(k);         
    }
    fibo_aux(i - 1, k, j + k );
}

}

Vlad