[英]JAVA for loop: all except a specified number
I need this for an array, but basically the idea is that a for
loop will run, and whatever number you tell it to skip, it won't do. 我需要一个数组,但是基本上的想法是要运行一个
for
循环,无论您告诉它跳过什么数字,它都不会执行。 So for(int x=0; x<50; x++)
if I want 1-50 except 22, how would I write that? 所以
for(int x=0; x<50; x++)
如果我想要1到22以外的1到50,我该怎么写呢?
This would give me the ability to skip a certain number in my array. 这将使我能够跳过数组中的某个数字。
Sorry if this is an extremely simple question, I am not too familiar with Java. 抱歉,如果这是一个非常简单的问题,我对Java不太熟悉。
Make use of continue
, something like this: 利用
continue
,如下所示:
for(int x=0; x<50; x++) {
if(x == 22)
continue;
// do work
}
Suggested reading: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html 建议阅读: http : //docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
public static final void doSkippedIteration(final int[] pArray, final int pSkipIndex) {
for(int i = 0; i < pSkipindex; i++) {
// Do something.
}
for(int i = pSkipIndex + 1; i < pArray.length; i++) {
// Do something.
}
}
You would have to do some basic check to see whether pIndex
lies within the confines of the array. 您必须进行一些基本检查,以查看
pIndex
是否位于数组的范围内。 This saves you from having to perform a check for every single iteration, but does require you to duplicate your code in this specific example. 这使您不必每次都进行检查,但是确实需要在此特定示例中重复代码。 You could of course avoid this by wrapping the code in a wider control block which handles the two iterations in a cleaner manner.
您当然可以通过将代码包装在更宽的控制块中来避免这种情况,该控制块以更简洁的方式处理两次迭代。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.