英文:
For loop within if statement in Java
问题
以下是翻译好的部分:
我有一段代码,在其中我需要多次重复一个操作,因此基本的if语句不够用。我的解决方案是在if语句内部使用for循环。我只是想知道是否有更有效的方法来解决这个问题。我知道这是基础中的基础,但我对Java还相对新手。提前感谢。
以下是代码示例:
int a = 20;
int b = a - anObject.getValue();
if (anObject.getValue() == a)
{
for (int x = 0; x < a; x++)
{
//需要重复的操作
}
}
else
{
for (int y = 0; y < b; y++)
{
//需要重复的其他操作
}
}
英文:
I've got a segment of code in which I'm having to repeat an action a number of times so a basic if statement won't suffice. My solution was to use For loops within the if statement. I just wondered if there's a more efficient way of going about this. I know it's 101 stuff but I'm fairly new to Java. Thanks in advance.
Code example below:
int a = 20
int b = a - anObject.getValue()
if (anObject.getValue() == a)
{
for (int x = 0; x < a; x++)
{
//do stuff that needs repeating
}
}
else
{
for (int y = 0; y < b; y++)
{
//do other stuff that needs repeating
}
}
答案1
得分: 0
int a = 20;
int b = a - anObject.getValue();
int limit = b==0 ? a : b;
for (int i=0; i<limit; ++i) {
// do stuff that needs repeating
}
You don't need to call `getValue` twice.
int b = a - anObject.getValue();
int limit = b==0 ? a : b;
If the 'stuff' is different, i.e. you're trying to extract the algorithm.
int a = 20;
int b = a - anObject.getValue();
final int limit;
final IntConsumer consumer;
if (b == 0) {
limit = a;
consumer = i -> {
// do stuff
};
} else {
limit = b;
consumer = i -> {
// do other stuff
};
}
IntStream.range(0, limit).forEach(consumer);
(Notice the weird syntax.};
You could use a `for` loop instead of the `IntStream` statement(it'll be faster).
for (int i=0; i<limit; ++i) {
consumer.accept(i);
}
Or the good old "dumb" way of doing it, repeating the condition:
int a = 20;
int b = a - anObject.getValue();
int limit = b==0 ? a : b;
for (int i=0; i<limit; ++i) {
if (b == 0) {
// do stuff
} else {
// do other stuff
}
}
英文:
int a = 20;
int b = a - anObject.getValue();
int limit = anObject.getValue()==a ? a : b;
for (int i=0; i<limit; ++i) {
//do stuff that needs repeating
}
You don't need to call getValue
twice.
int b = a - anObject.getValue();
int limit = b==0 ? a : b;
If the 'stuff' is different, i.e. you're trying to extract the algorithm.
int a = 20;
int b = a - anObject.getValue();
final int limit;
final IntConsumer consumer;
if (b == 0) {
limit = a;
consumer = i -> {
// do stuff
};
} else {
limit = b;
consumer = i -> {
// do other stuff
};
}
IntStream.range(0, limit).forEach(consumer);
(Notice the weird syntax.};
You could use a for
loop instead of the IntStream
statement(it'll be faster).
for (int i=0; i<limit; ++i) {
consumer.accept(i);
}
Or the good old "dumb" way of doing it, repeating the condition:
int a = 20;
int b = a - anObject.getValue();
int limit = b==0 ? a : b;
for (int i=0; i<limit; ++i) {
if (b == 0) {
// do stuff
} else {
// do other stuff
}
}
专注分享java语言的经验与见解,让所有开发者获益!
评论