英文:
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;
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论