Why do I get unreachable statement error in Java?

544 Views Asked by At

I'm putting together a code for a hailstone sequence I found in an online tutorial, but in doing so I ran into an unreachable statement error. I don't know if my code is correct and I don't want advice in correcting it if I'm wrong(regarding the hailstone sequence, I want to do that myself..:) ). I just want help in resolving the "unreachable statement" error at line 19.

class HailstoneSequence {
    public static void main(String[] args) {
        int[][] a = new int[10][];
        a[0][0] = 125;
        int number = 125;

        for (int i = 0;; i++) {
            for (int j = 1; j < 10; j++) {
                if (number % 2 == 0) {
                    a[i][j] = number / 2;
                    number = number / 2;
                } else {
                    a[i][j] = (number * 3) + 1;
                    number = (number * 3) + 1;
                }
            }
        }

        for (int i = 0;; i++) {
            for (int j = 0; j < 10; j++) {
                System.out.println(a[i][j]);
            }
        }
    }
}
7

There are 7 best solutions below

0
NESPowerGlove On

Your first infinite loop of for(int i=0;;i++) stops any other code from being reached.

2
NPE On

This is an infinite loop:

for(int i=0;;i++){

Whatever comes after it never get executed (i.e. is unreachable).

0
coder On

There is an infinite loop @ line 7

0
starf On

In your first for loop:

for(int i=0;;i++){
....
}

You do not define the ending condition. e.g.

for(int i=0; i<10; i++){
....
}

Therefore the loop never exits.

0
Funonly On

You forgot to set an exit condition

for(int i=0;here;i++){

This might create unexpected behaviour.

0
venom On

Your first for statement (in the 6'th line) is an infinite loop therefore it stops further code to be reached.

for(int i=0;;i++)
0
AnkitSomani On

You have problem at line number 6 in your first for loop.

 for(int i=0;;i++) {

Here since your don't have any exit conditions, code is going in the infinite loop and the loop never exits. Whatever outside the scope of this for loop will be unreachable since your first loop is never existing.

Consider adding the exit condition (such as break or return etc.) inside your for loop to prevent this behavior.