user3889963
user3889963

Reputation: 477

Why do I get unreachable statement error in Java?

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

Upvotes: 2

Views: 557

Answers (7)

venom
venom

Reputation: 101

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

Upvotes: 1

AnkitSomani
AnkitSomani

Reputation: 1192

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.

Upvotes: 0

Funonly
Funonly

Reputation: 283

You forgot to set an exit condition

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

This might create unexpected behaviour.

Upvotes: 2

starf
starf

Reputation: 1093

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.

Upvotes: 5

coder
coder

Reputation: 1941

There is an infinite loop @ line 7

Upvotes: 2

NPE
NPE

Reputation: 500327

This is an infinite loop:

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

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

Upvotes: 10

NESPowerGlove
NESPowerGlove

Reputation: 5496

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

Upvotes: 3

Related Questions