1
public void calculate(int input) {

inputField.setText("" + input);

while (input >= 1) {

    if (input % 2 == 0) {
        input = input / 2;
    } else {
        input = (input * 3) + 1;
    }
    output.append("" + input);
    }

}

The output variable is a JTextArea and inputField is a JTextField where the user enters an integer.

I call the method and initialize the input variable here:

@Override
public void actionPerformed(ActionEvent e) {

    input = Integer.parseInt(inputField.getText());
    calculate(input);

    }

}

Every time the value of input is even, it is divided by 2 so it should eventually reach 1, correct? Then why does this while loop cause an infinite loop?

Bytecode
  • 47
  • 6
  • 3
    hint : what happens when `input == 1`? – TheLostMind Aug 11 '14 at 08:58
  • 1 4 2 1 4 2 1 4 2 1 4 2 1 4 2 1 4 2 – Dawood ibn Kareem Aug 11 '14 at 08:59
  • "Every time the value of input is even, it is divided by 2 so it should eventually reach 1, correct? Then why does this while loop cause an infinite loop?" - perhaps you could ask yourself, where the difference between your program and your assumption lies that the program should exit when reaching "1". – Smutje Aug 11 '14 at 09:00
  • Thanks everyone. The biggest mistake I made here was indeed thinking the loop would stop executing when input reached 1. – Bytecode Aug 11 '14 at 09:05

3 Answers3

3

The problem is your condition - because even if you reach 1, the loop will continue. Replace while (input >= 1) with while (input > 1)

Marwie
  • 3,177
  • 3
  • 28
  • 49
0

This gives an infinite loop because input can never get to zero or below. There is no even number >=1 which when halved gives zero, and no odd number >=1 which when tripled gives -1. So input will always be >=1 and you have an endless loop.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
0

If the Collatz conjecture is true that loop will always reach 1 -- the problem is that you don't stop looping at 1 :)

Change while (input >= 1) to while (input > 1).

pdw
  • 8,359
  • 2
  • 29
  • 41