简体   繁体   中英

Why does this while loop cause an infinite loop?

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?

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM