Search code examples
javaif-statementwhile-loopsubtraction

Shortening many if statements in a while loop in Java


How can I shorten many subtractions of the exact same nature in a while loop in Java? I feel like it's very redundant and there can definitely be a shorter way.

while (x != 0) {
        if (x - 100 >= 0) {
            x -= 100;
        }

        if (x - 50 >= 0) {
            x -= 50;
        }

        if (x - 25 >= 0) {
            x -= 25;
        }

        ...

Solution

  • First of all, you don't need to subtract and compare to zero, instead just compare to the number you are subtracting.

    while (x != 0) {
            if (x >= 100) {
                x -= 100;
            }
    
            if (x >= 50) {
                x -= 50;
            }
    
            if (x >= 25) {
                x -= 25;
            }
    
            ...
    

    Secondly, what you're asking is a case by case problem. You could shorten the code above like this:

    int[] nums = {100, 50, 25};
    
    while (x != 0) {
        for (int num : nums) {
            if (x >= num) {
                x -= num;
            }
        }
    }