snipersu28
snipersu28

Reputation: 11

Skip one iteration in a for loop

How can I skip one iteration of a for loop like this one:

for (int i = 65; i <= 90; i++) {
  if (!(i == 73)) {
    uniq.add((char) i);
  }
}

uniq should contain the alphabet, excluding 'I'. Are there any other ways to solve this? I'm just starting Java, and I'm trying to do this as simply as possible.

Upvotes: 1

Views: 5990

Answers (4)

Rezwan Azfar Haleem
Rezwan Azfar Haleem

Reputation: 1228

Direct implementation of the following code should work. With this method you would not be require to know corresponding ACSII or Unicode representations of letters.

for (int i = 'A'; i <= 'Z'; i++) {
  if (i != 'I') {
    uniq.add((char) i);
  }
}

Upvotes: 1

dimo414
dimo414

Reputation: 48824

Under the covers, a char is just a number between 0 and 65,535 (an unsigned short), and that means you can do arithmetic on chars, and even use them in loops. This can make a lot of text-twiddling code much easier to read. Consider:

for (char c = 'A'; c <= 'Z'; c++) {
  if (c != 'I') {
    uniq.add(c);
  }
}

Now it's immediately clear we're looping over the ASCII alphabet, adding each char to a list, and skipping 'I'.


As @C.B. and I discussed in the comments, you could also do:

for (char c = 'A'; c <= 'Z'; c++) {
  uniq.add(c);
}
uniq.remove('I');

However depending on your data stricture, this could be problematic. If uniq is a List, the .remove() operation has to loop over the whole list, which is needlessly wasteful.

Upvotes: 2

null
null

Reputation: 2140

You could try something like this:

for (int i = 65; i <=90; i++) {
    if (i == 73) {
        continue;
    }                    // An else is not needed because the continue would skip
    uniq.add((char) i);  // over all of the code after it.
}

The keyword continue skips over the current iteration of the for loop, although for a single case such as this, I would expect your implementation to be just as, if not more, simple.
However, one thing I would change with your code is switching !(i==73) to i != 73, as the latter is more common and more readable.

Upvotes: 4

John Hodge
John Hodge

Reputation: 1715

It looks like you're probably already doing it one of the simplest ways possible.

A more verbose, but perhaps less elegant (although arguably easier to read) way to accomplish the same thing could be something like the following:

for (int i = 65; i < 73; i++) {
            uniq.add((char) i);
}

for (int i = 74; i <= 90; i++) {
            uniq.add((char) i);
}

When you're writing source code I like to think that you're writing for a human, not the computer. Try to emphasize readability over shortness.

Upvotes: 0

Related Questions