2

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]);
            }
        }
    }
}
Tiny
  • 27,221
  • 105
  • 339
  • 599
user3889963
  • 477
  • 3
  • 6
  • 17

7 Answers7

10

This is an infinite loop:

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

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

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • My intentions were to specify a two dimensional array whose horizontal length is fixed at 10, while the vertical length is dependent on the length of the sequence. What do you propose? – user3889963 Aug 08 '14 at 15:09
  • @user3889963 You need to initialise each 'column' in your array. These can be varying lengths. In your for-loop you can then use `a.length` and `a[i].length`. – starf Aug 08 '14 at 15:20
5

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.

starf
  • 1,063
  • 11
  • 15
3

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

NESPowerGlove
  • 5,496
  • 17
  • 28
2

There is an infinite loop @ line 7

coder
  • 1,901
  • 5
  • 29
  • 44
2

You forgot to set an exit condition

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

This might create unexpected behaviour.

Funonly
  • 283
  • 1
  • 13
1

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++)
venom
  • 101
  • 1
  • 7
0

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.

AnkitSomani
  • 1,152
  • 8
  • 9