Java中if语句中的For循环
我有一段代码,其中我必须重复一个动作很多次,所以一个基本的if语句是不够的。我的解决方案是在if语句中使用For循环。我只是想知道是否有更有效的方法来解决这个问题。我知道这是101个东西,但我对Java还是相当陌生的。提前谢谢 代码示例如下:Java中if语句中的For循环,java,Java,我有一段代码,其中我必须重复一个动作很多次,所以一个基本的if语句是不够的。我的解决方案是在if语句中使用For循环。我只是想知道是否有更有效的方法来解决这个问题。我知道这是101个东西,但我对Java还是相当陌生的。提前谢谢 代码示例如下: int a = 20 int b = a - anObject.getValue() if (anObject.getValue() == a) { for (int x = 0; x < a; x++) {
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
}
}
inta=20
int b=a-anObject.getValue()
if(anObject.getValue()==a)
{
对于(int x=0;x
如果“东西”不同,即您试图提取算法
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);
(注意奇怪的语法。)
您可以使用for
循环代替IntStream
语句(这样会更快)
for(int i=0;i
如果“东西”不同,即您试图提取算法
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);
(注意奇怪的语法。)
您可以使用for
循环代替IntStream
语句(这样会更快)
for(int i=0;iIt取决于哪些内容需要重复,哪些内容需要重复?看起来像是某个特定方法发挥作用的候选者:int val=anObject.getValue();if(val==a){myMethod(a);}else{myMethod(b);}
这取决于哪些内容需要重复,哪些内容需要重复?看起来像是某个特定方法发挥作用的候选者:int val=anObject.getValue();if(val==a){myMethod(a);}else{myMethod(b);}
@user85421我在做这个假设。我已经扩展了我的答案。@user85421哦,是的,谢谢。我太专注于把IntStream
胡说八道说对了。谢谢你到目前为止的建议。我应该澄清一下,抱歉。我说的其他东西是“不同”的东西。@yoshmv35这就是“重复”的意思“这让我很困惑-我开始认为这是重复的,你对同一个代码应用了稍微不同的算法参数化版本。霍丁。对不起,是的,我只是指“做一些事情”或“做其他事情”的迭代。”。谢谢你的帮助!@user85421我在做这个假设。我已经扩展了我的答案。@user85421哦,是的,谢谢。太专注于把IntStream
胡说八道弄对了。谢谢你到目前为止的建议。我应该澄清一下,抱歉。我说的其他东西是“不同”的东西。@yoshmv35这就是“重复”的意思“这让我很困惑-我开始认为这是重复的,而你对同一代码应用了稍微不同的算法参数化版本。霍丁。对不起,是的,我只是指“做事情”或“做其他事情”的迭代。谢谢你的帮助!
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);
for (int i=0; i<limit; ++i) {
consumer.accept(i);
}
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
}
}