简体   繁体   中英

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. So for(int x=0; x<50; x++) if I want 1-50 except 22, how would I write that?

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.

Make use of continue , something like this:

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

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM