# Fibonacci Number Calculator

• 11-28-2012, 12:26 AM
Dr_DerpyHooves
Fibonacci Number Calculator
Hello, I have been learning Java for a while now and I have run into an roadblock with my code. What I am trying to do is run a Fibonacci Number Calculator while using a recursive method and not "for loopers".
This is what I have so far.

import java.util.*;
public class Driver
{
private int temp = 0;
private Scanner in;

public Driver()
{
in = new Scanner(System.in);
}
public void getBase()
{
System.out.println("Hello and welcome to the Fibonacci Number Calculator!!!");
System.out.print("First off what number position do us to calculate the Fib Value of? ");
temp = in.nextInt();
}
public static void main(String[] args)
{
FibonacciNumbers fnum = new FibonacciNumbers();
}
public void displayNum()
{
System.out.print("The fib num of " +temp);
System.out.println(" is " +fnum.calcFibonacci(temp) );
}
}

public class FibonacciNumbers
{

public int calcFibonacci(int number)
{

if ( ( number == 0 ) || ( number == 1 ) )
{
return number;
}

else
{
return calcFibonacci( number - 1 ) + calcFibonacci( number - 2 );
}

}

}

The problem I am running into is that the variable I need to display the base also needs to be in the Driver which is "static" while also needing the Scanner in the same method because I need to run and return the value of the method in the other class.
Any help is appreciated.
• 11-28-2012, 01:45 AM
Re: Fibonacci Number Calculator
I am not really understand what your question was. But what I can see in you code is that you cannot run it correctly. What you need to change in my opinion are:

1. In the main() method you should create an instance of the Driver class.
2. Call the getBase() method from this instance.
3. Call the displayNum() method from this instance.
4. Move the creation of the FibonacciNumbers instance into the displayNum() method.

Other improvement that you can make is move the temp variable and the scanner into the getBase() method. Instead of returning void this method can return the number inputted by the user. And then pass this number to the displayNum() method by adding a parameter to this method. So you'll have new signature for this method like:

Code:

```public int getBase() { ... } public void displayNum(int number) { ... }```
• 11-28-2012, 03:56 AM
DarrylBurke
Re: Fibonacci Number Calculator