Java - TIMEOUT(无限循环)错误

时间:2015-07-04 11:15:17

标签: java loops infinite

我们的教师给我们介绍JAVA类的一个练习问题是给我一个创建无限循环的错误。我想知道如何在没有此错误的情况下获得相同的输出(测试输出显示在屏幕截图中)。

关于作业的说明如下:

编写一个名为flipLines的方法,该方法接受输入文件的Scanner作为参数,并向控制台写入相同文件的内容,并按顺序颠倒连续的行对。程序应该以相反的顺序打印第一对线,然后以相反的顺序打印第二对,然后以相反的顺序打印第三对,依此类推。输入文件可以有奇数行,在这种情况下,最后一行打印在其原始位置。

此图片是错误的屏幕截图以及我在网站上的代码。 http://www.toptal.com/emberjs/a-thorough-guide-to-ember-data

这是我的第一篇文章,希望我能正确格式化。

以防万一,这里又是我的代码:

    public static void flipLines(Scanner input)  
    { 



    int x = 0;
    String evenLine = "";  
    String oddLine = "";  
    boolean value = true;

    while (value = true)
    {

        if (input.hasNextLine())
        {
            x++;

        }
        else
        {
            value = false;
        }
    }

    for (int i = 0; i < x; i++)
    {
        if (i < x && i % 2 == 0)
        {
            evenLine = input.nextLine();
            System.out.println(evenLine);            
        }
        else
        {
            continue;
        }

    }
    for (int j = 0; j < x; j++)
    {
        if (j < x && j % 2 != 0)
        {
            oddLine = input.nextLine();
            System.out.println(oddLine);
        }
        else
        {
            continue;
        }
    }
}

1 个答案:

答案 0 :(得分:2)

更改作业

while (value = true)

比较

while (value == true)

value = truetrue分配给value并返回true,这意味着循环永远不会结束。

编辑:

此外,input.hasNextLine()将始终返回true,因为直到while循环之后才读取任何行,这就是循环永远不会结束的原因。

在没有实际读取行的情况下,您无法找到输入行的数量。

你的for循环也不会做你认为他们应该做的事情。仅仅因为你跳过for循环的迭代并不意味着你跳过一行输入。

你需要的是一个循环,在每次迭代中读取两行(假设有两行可用)并以相反的顺序打印它们。

String line1 = null;
while (input.hasNextLine()) {
    line1 = input.nextLine();
    if (input.hasNextLine()) {
        String line2 = input.nextLine();
        System.out.println(line2);
        System.out.println(line1);
        line1 = null;
    }
}
if (line1 != null)
    System.out.println(line1);