Java程序涉及

Java程序涉及,java,Java,我正在尝试编写以下程序序列 序列中的前三个数字是1,1,2。序列中的每一个其他数字是前面三个数字的总和。程序应提示用户输入限制;当序列中的当前编号大于或等于此限值时,程序将停止 例如,如果我写的限制是123,我应该得到:1 1 2 4 7 13 24 44 81 我尝试了以下方法: import jpb.*; public class XiaolinSequence { public static void main(String[] args) { SimpleIO

我正在尝试编写以下程序序列

序列中的前三个数字是1,1,2。序列中的每一个其他数字是前面三个数字的总和。程序应提示用户输入限制;当序列中的当前编号大于或等于此限值时,程序将停止

例如,如果我写的限制是123,我应该得到:1 1 2 4 7 13 24 44 81

我尝试了以下方法:

import jpb.*;

public class XiaolinSequence {

    public static void main(String[] args) {
        SimpleIO.prompt("Enter a limit on the largest number to be displayed:");
        String userInput = SimpleIO.readLine();
        int counter = Integer.parseInt(userInput);

        int older = 1;
        int old = 1;
        int current = 2;
        while (current < counter) {
            int nextNumber = older + old + current;
            older = old;
            old = current;
            current = nextNumber;
            System.out.println(nextNumber);
        }
    }

}

但是我在打印序列时遇到了麻烦。

好的,因为人们因为你的SimpleIO而抨击我,所以请使用任何你想读取的输入。相反,我要指出代码中的一个逻辑缺陷

要使程序正常运行,您需要打印旧版本而不是当前版本,如下所示:

while (older < counter) 
{
    System.out.println(older);

    final int nextnumber = older + old + current;
    older = old;
    old = current;
    current = nextnumber;
}
然后代码就可以工作了


哦,顺便说一下,在开始循环之前,别忘了打印出12

您需要更改打印内容的方式

丢失的1 2永远不会打印,因为它们永远不会存储在nextnumber中,nextnumber是您打印过的唯一变量

您将获得额外的149,因为您打印nextnumber而不检查它的值大于限制

对我来说,以下代码的输出是1 1 2 4 7 13 24 44 81,都在新行上

int counter=123; // replaced IO code so I did not have to download the jar.
int older=1;
int old =1;
int current=2;

System.out.println(older);  // prints the first 1
System.out.println(old);  // prints the second 1
System.out.println(current);  // prints the 2

while(current<counter){
    int nextnumber=older+old+current;
    older=old;
    old=current;
    current=nextnumber;
    if(nextnumber <= counter)       
    {
        System.out.println(nextnumber);
    }
}

当我输入一个计数器时,比如说123,我没有得到我需要的正确输出。请更详细地描述你实际得到的输出。看起来应该可以。你得到的结果是什么?看起来可能是一个比一个差。在检查下一个数字是否超出您的限制之前,请先打印下一个数字。没有足够快地完成此操作,但是@TishaMoisha另一个解决方案在这里。我假设SimpleIO在jpb中。*…FiiIline。编辑答案。这也是我最初的解决方案。但是有一种更简单的方法。只需在循环中打印旧代码。谢谢colin是的,您的代码可以正常工作并且excellente@GCrec,我同意,这个代码可以改进。我只是想说明从OP到工作解决方案的步骤。@TishaMoisha对于水平输出使用System.out.print而不是System.out.println。@TishaMoisha在while循环之前,执行以下操作:System.out.printolder+,+old+,+current;。然后在if currentint counter=123; // replaced IO code so I did not have to download the jar. int older=1; int old =1; int current=2; System.out.println(older); // prints the first 1 System.out.println(old); // prints the second 1 System.out.println(current); // prints the 2 while(current<counter){ int nextnumber=older+old+current; older=old; old=current; current=nextnumber; if(nextnumber <= counter) { System.out.println(nextnumber); } }