Reputation:
I have the following simple recursive Fibonacci code:
public class FibPrac5202016
{
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter index number: ");
int integer = input.nextInt();
FibPrac5202016 object = new FibPrac5202016();
System.out.println(object.operation(integer));
}
public static long operation(long n) {
if(n==0)
return 0;
if(n==1)
return 1;
try {
if( n < 0)
throw new Exception("Positive Number Required");
}
catch(Exception exc)
{
System.out.println("Error: " + exc.getMessage());
}
return operation((n-1))+operation((n-2));
}
}
As I recently learned about exceptions, I'm trying to use that here when the user inputs negative integer.However, my program runs into StackOverflowError.
Upvotes: 1
Views: 46
Reputation: 387
the problem is that these throws a execcion within a try block and this creates a cycle in which is testing the code and as always will be a smaller number than 0 always threw the exception infinitely until the exception is given
Exception in thread "main" java.lang.StackOverflowError
I think the solution is to make the program a stop when you find a number less than 0
as follows
public class FibPrac5202016 {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter index number: ");
int integer = input.nextInt();
FibPrac5202016 object = new FibPrac5202016();
System.out.println(object.operation(integer));
}
public static long operation(long n) {
if(n==0)
return 0;
if(n==1)
return 1;
try
{
if( n < 0)
throw new Exception("Positive Number Required");
}
catch(Exception exc)
{
System.out.println("Error: " + exc.getMessage());
//return -1;
}
return operation((n-1))+operation((n-2));
}
}
Upvotes: 0
Reputation: 201439
Well yes, because you recurse after you catch an Exception
. You could trivially fix it by returning -1
in the catch
.
catch(Exception exc)
{
System.out.println("Error: " + exc.getMessage());
return -1;
}
or not throwing an Exception
in the first place like
public static long operation(long n) {
if (n < 0) {
return -1;
} else if (n == 0) {
return 0;
} else if (n == 1 || n == 2) {
return 1;
}
return operation((n-1))+operation((n-2));
}
or you could implement the Negafibonaccis. And, you could extend it to support BigInteger
(and optimize with memoization) like
private static Map<Long, BigInteger> memo = new HashMap<>();
static {
memo.put(0L, BigInteger.ZERO);
memo.put(1L, BigInteger.ONE);
memo.put(2L, BigInteger.ONE);
}
public static BigInteger operation(long n) {
if (memo.containsKey(n)) {
return memo.get(n);
}
final long m = Math.abs(n);
BigInteger ret = n < 0 //
? BigInteger.valueOf(m % 2 == 0 ? -1 : 1).multiply(operation(m))
: operation((n - 2)).add(operation((n - 1)));
memo.put(n, ret);
return ret;
}
Upvotes: 1