Search code examples
javaunreachable-code

unreachable statement error obtained using labeled break


Here, I want to take few lines as input until only '0' is entered in one of the lines. And print these lines in the reverse order of how they were input. Howver, I'm facing difficulty in usage of the labeled break. I'm getting the following error:

PrintRevOrderLines.java:17: error: unreachable statement
                System.out.println("\nReversed order of lines is as follows..\n");
                ^
1 error

I am unable to understand why line 17 is unreachable. I know I can easily use only the 'break' (not the labeled break) statement, allow 'count' variable to be incremented one more than actually it should be and then, while printing, do like this: for(int i=count-1;i>=0;i--) and avoid printing 0, but i want to

  1. stop the value of count at the correct value and,
  2. know why line 17 is unreachable

My code is as follows:

import java.io.*;
class PrintRevOrderLines
{
    public static void main(String[] args) throws IOException
    {   
        int count = 0;
        String inputs[] = new String[100];
        System.out.println("Enter 0 and hit enter to stop inputting values..\n");
        BufferedReader B = new BufferedReader(new InputStreamReader(System.in));
        for(int i=0;;i++)
        thisblock:
        {
            inputs[i] = B.readLine();
            if(inputs[i].charAt(0)=='0'){break thisblock;}
            count++;
        }
        System.out.println("\nReversed order of lines is as follows..\n");
        for(int i=count;i>=0;i--)
        {
            System.out.println(" "+inputs[i]);
        }
    }
}

Solution

  • What happen is that your for loop will never end, since you don't put a termination condition, nor you "break" it inside the body of the for. Try this and you will see:

    for (int i = 0;; i++)
        System.out.println("here");
    System.out.println("\nReversed order of lines is as follows..\n");
    

    You will get the same "unrecheable code".

    Edit:

    Try this:

    boolean flag = false;
    for (int i = 0;; i++) {
        thisblock: {
            inputs[i] = B.readLine();
            if (inputs[i].charAt(0) == '0') {
                flag = true;
                break thisblock;
            }
            count++;
        }
        if (flag)
            break;
    }
    

    Output:

    Reversed order of lines is as follows..
    
     0
     3
     2
     1