MZiskaO MZiskaO - 1 month ago 7
Java Question

Producing the Nth value of Fibonacci Sequence in Java

This is the program I'm running to print the nth value of the Fibonacci sequence, but I've come across the problem that when I enter an invalid value I defined, it still runs the loop either way. For example if I enter 0, it will print:

"Not a valid number
The 0 value of the Fibonacci Sequence is 0"

Hopefully someone can point out where I made my error, I've reviewed all of my bracketing and I can't find where the mistake might be

//position is user input for nth position, fold2 and fnew will calculate fSequence to find value

int position, fold1, fold2, fNew, loopCount;

//telling user what program will do and stipulations on how to get program to execute correctly
System.out.println("This program will tell you the nth value of the Fibonacci sequence.");
System.out.println("Enter an integer (1 - 46):");
position = keyboard.nextInt();

fold1 = 0;
fold2 = 1;

//setting upper parameters for limit on given positions
if (position < 1 || position > 46){
System.out.println("Not a valid number");
}
else {
for (loopCount = 0; loopCount < position; loopCount++ ){
fNew = fold1 + fold2;
fold1 = fold2;
fold2 = fNew;
}
}

System.out.println("The " + position + " of the Fibonacci Sequence is " + fold1);

Answer

Your System.out.println("The " + position + " of the Fibonacci Sequence is " + fold1); is outside the else scope, hence executed no matter what the condition is.

Your code should read,

 if (position < 1 || position > 46){
        System.out.println("Not a valid number");
    } 
    else {
        for (loopCount = 0; loopCount < position; loopCount++ ){
            fNew = fold1 + fold2;
            fold1 = fold2;
            fold2 = fNew;
            System.out.println("The " + position + " of the Fibonacci Sequence is " + fold1);                       
        }
    }   
Comments