简化Java中while循环中的许多if语句

huangapple go评论60阅读模式
英文:

Shortening many if statements in a while loop in Java

问题

在Java的while循环中,如何缩短许多相同性质的减法操作?我觉得这样做非常冗余,肯定有更简洁的方法。

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

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

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

    ...
}
英文:

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

        ...

答案1

得分: 1

首先,您无需减去并与零进行比较,而只需与您正在减去的数字进行比较。

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

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

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

    ...

其次,您所询问的是一个逐案例的问题。您可以像下面这样简化上面的代码:

int[] nums = {100, 50, 25};

while (x != 0) {
    for (int num : nums) {
        if (x >= num) {
            x -= num;
        }
    }
}
英文:

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

huangapple
  • 本文由 发表于 2020年9月23日 18:30:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/64025975.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定