0

We have an assignment to write a program finding the nth Fibonacci number.

On the web, there are some standard mathematical equations for this, but that would just defeat the purpose of this assignment if I use those formulas.

I have my current code down here(with some sketchy back up code stuff), but I am really confused about what I am writing down here, the loop I have written in my code is not really working at all. :|

Also, would this program represent a linear equation or a quadratic or possibly polynomial equation?

```
import java.util.InputMismatchException;
import java.util.Scanner;
public class FibonacciNumbers {
/**
* @param args
*/
static int nthNumber;
public static int fibonacciCalculate (int n) {
int i;
int [] x = new int[n];
x[0]=1;
x[1]=1;
/*for (i=0; i<n; i++)
{
x[i+2]=x[i]+x[i+1];
}*/
for (i=2; i<n-1; i++)
{
x[n] = x[n-2]+x[n-1];
}
nthNumber=x[n-1];
return nthNumber;//returns the result to the main method, terminates fibonacciCalculate method
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int n = 0;
Scanner sc = new Scanner (System.in);
boolean checkException = false;//create a boolean variable called "checkException"
//and initiate its default value
do {
System.out.println("Enter an integer n for the nth Fibonacci number you want to find: ");
try {
n = sc.nextInt();
checkException = true;//sets the boolean value to true, will cause
//the do-while loop to exit
}
catch (InputMismatchException e)//catches all number format exceptions
{
System.out.println("Invalid data. Please enter an integer that is greater than 0.");
checkException = false;//sets boolean value to false, continues the loop
}
try {
nthNumber= fibonacciCalculate (n);//calls the fibonacciCalculate method to obtain
//the integer nthNumber, the nth Fibonacci number
checkException = true;
}
catch (ArrayIndexOutOfBoundsException a)
{
System.out.println("ohlalaInvalid data. Please enter an integer that is greater than 0.");
checkException = false;//sets boolean value to false, continues the loop
}
} while (checkException == false || n<=0);//remains in loop as long as the boolean variable is false
switch(n)
{
case 1: System.out.println("Your first Fibonacci number is "+nthNumber);
break;
case 2: System.out.println("Your second Fibonacci number is "+nthNumber);
break;
case 3: System.out.println("Your third Fibonacci number is "+nthNumber);
break;
default : System.out.println("Your "+n+"th Fibonacci number is "+nthNumber);
break;
}
}
}
```

*Edited 6 Years Ago by flyingcurry*: n/a