Search code examples
javaloopsinfinite

Java - TIMEOUT (Infinite loop) error


One of the practice problems our instructor gave us for an intro to JAVA class is giving me an error for creating an infinite loop. I would like to know how to get the same output that I am getting (test output is shown in the screenshot) without this error.

The instructions on the assignment are as follows:

Write a method named flipLines that accepts as its parameter a Scanner for an input file and that writes to the console the same file's contents with successive pairs of lines reversed in order. The program should print the first pair of lines in reverse order, then the second pair in reverse order, then the third pair in reverse order, and so on. An input file can have an odd number of lines in which case the last line is printed in its original position.

This image is a screenshot of the error along with my code on the website. My error screenshot

This is my first post so hopefully I formatted this correctly.

Just in case, here's my code again:

    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;
        }
    }
}

Solution

  • change your assignment

    while (value = true)
    

    to comparison

    while (value == true)
    

    value = true assigns true to value and returns true, which means the loop will never end.

    EDIT :

    In addition, input.hasNextLine() will always return true since you are not reading any line until after the while loop, which is why that loop never ends.

    You can't find the number of input lines without actually reading the lines.

    Your for loops also don't do what you think they should do. Just because you skip an iteration of the for loop doesn't mean that you skip a row of the input.

    What you need is a single loop that reads two lines (assuming there are two lines available) in each iteration and prints them in reversed order.

    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);