Print out odd numbers 0-100, excluding X, Y, Z

10,440

Solution 1

for (int i=0; i<100; i++) {
    if ( (i % 2 !=0) && i!=5 && i!=9 && i!=11) {
        System.out.println(i)
    }
}

It's bad practice to write it without the brackets since it's too easy to make an error when adding more lines later on. Also, you're probably writing Java and not JavaScript.

Solution 2

(with JDK 7)

Set<Integer> exclusions = new HashSet<>(Arrays.asList(5, 9, 11)); //syntactic sugar from JDK 7
for (int i=0; i<100; i++) {
    if(i % 2 == 0 || exclusions.contains(i))  // if pair OR in exclusions list, isn't interesting
       continue; // continue allows to say: "isn't interesting, take me to the next value
    System.out.println(i); // Oh yeah, this one is interesting! It's an odd! print it!
}

(with JDK 5/6)

Set<Integer> exclusions = new HashSet<Integer>(Arrays.asList(5, 9, 11));
for (int i=0; i<100; i++) {
    if(i % 2 == 0 || exclusions.contains(i))
       continue;
    System.out.println(i);
}

of course, there is other ways to achieve the tasks, but I enjoy this one.

Besides, the use of Arrays.asList is a good tips to [initialize the Setinline][1].

It replaces this traditional boilerplate code:

Set<Integer> exclusions = new HashSet<Integer>();
   exclusions.add(5);
   exclusions.add(9);
   exclusions.add(11);
Share:
10,440
Littlev
Author by

Littlev

Updated on June 09, 2022

Comments

  • Littlev
    Littlev almost 2 years

    This is obviously a "Homework style" task, but I have issues with grasping how I can exclude a certain set of numbers. I understand how I can write out the odd numbers from 0-100, but I fail to comprehend any answers I've found, or tried to find, about how to exclude pre-set numbers of choice.

    Basically, what I want to happen is the following: The program writes all odd numbers from 1-100. Lets say I don't want the numbers 5,9 or 11 to be displayed, but I want my program to continue, how do I make that happen?

    I have two different sets of code (I don't know which is easier to use in this context, so I'm including both of them):

    for (int i=0; i<100; i++)
    
                if (i % 2 !=0)
            System.out.println(i)
    

    and

    for (int i=1; i<100; i=i+2)
    System.out.println(i)