用Java生成Fibonacci序列的第n个值

用Java生成Fibonacci序列的第n个值,java,fibonacci,Java,Fibonacci,这是我正在运行的打印斐波那契序列第n个值的程序,但我遇到了一个问题,当我输入我定义的无效值时,它仍然以任何方式运行循环。例如,如果我输入0,它将打印: “不是一个有效的数字 斐波那契序列的0值为0“ 希望有人能指出我犯错误的地方,我已经检查了我所有的括号,但我找不到错误可能在哪里 //position is user input for nth position, fold2 and fnew will calculate fSequence to find value int positio

这是我正在运行的打印斐波那契序列第n个值的程序,但我遇到了一个问题,当我输入我定义的无效值时,它仍然以任何方式运行循环。例如,如果我输入0,它将打印:

“不是一个有效的数字 斐波那契序列的0值为0“

希望有人能指出我犯错误的地方,我已经检查了我所有的括号,但我找不到错误可能在哪里

//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);
//位置是第n个位置的用户输入,fold2和fnew将计算fSequence以查找值
int位置、fold1、fold2、fNew、loopCount;
//告诉用户程序将做什么,以及如何让程序正确执行的规定
println(“此程序将告诉您斐波那契序列的第n个值。”);
System.out.println(“输入一个整数(1-46):”;
位置=键盘.nextInt();
fold1=0;
fold2=1;
//设置给定位置上的上限参数
如果(位置<1 | |位置>46){
System.out.println(“不是有效数字”);
} 
否则{
用于(loopCount=0;loopCount
上一个
系统.out.println
在您的
else
之外,因此它总是被调用。您应该将其移动到
中,否则

您得到了这一行:

 System.out.println("The " + position + " of the Fibonacci Sequence is " + fold1);
在else之后,因此它甚至在if语句之后,因此它在任何情况下都会执行,将它放在末尾的else括号内。

System.out.println(“斐波那契序列的“+位置+”是“+fold1”)
不在
else
范围内,因此无论条件如何都会执行

你的代码应该是

 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);                       
        }
    }   
if(位置<1 | |位置>46){
System.out.println(“不是有效数字”);
} 
否则{
用于(loopCount=0;loopCount
将最后一行上移一行,使其位于
else
语句的大括号内。IMHO,您应该声明变量,使其接近第一次使用的位置。在一开始就声明所有这些只会让读者感到困惑。这是我忽略的一点,如此简单的概念。谢谢