3

So I started learning Java only a few days ago and I'm doing really well except for this one exercise that boggles my mind. So the exercise is to "Write a program which displays all numbers from 1 to 30 indivisible by 3". So this is easy:

class numbers {
    public static void main (String args[]) {
        for (int i = 0; i <=30; i++){
            switch(i % 3){
                case 0 :
                    break;
                default :
                    System.out.println(i);
                    break;
            }
        }
    }
}

Except one of the variants says "use break after divisibility by 3 is detected. Now I'm not sure if hte break used in the code above is correct, as it is a part of switch. I was wondering if there was an other way to do it.

mkobit
  • 43,979
  • 12
  • 156
  • 150
shooqie
  • 950
  • 7
  • 17
  • This seems to give the desired output. What's your concern about the code? – shree.pat18 May 02 '15 at 06:32
  • Do you mean you want a statement inside the `switch` that breaks out of the `for` loop? Try named loops. See http://stackoverflow.com/questions/886955/breaking-out-of-nested-loops-in-java, which should apply even though you don't have a nested loop. – ajb May 02 '15 at 06:33
  • It IS the desired output. There a few variants to it, though - like "use `continue`", "don't use `continue`" etc. One of them says "use `break` when divisibility by 3 is detected" and and I'd like to know if there is an other way to do so - i.e. with `break` but without `switch`. – shooqie May 02 '15 at 06:35

3 Answers3

5

Some fixes:

  1. class names should start with Upper letter, name class Numbers, not numbers
  2. start iterating from 1, not from 0, because you are displaying numbers in range [1..30].
  3. Because here you have only 2 possibilities (is or is not indivisible), replace switch with if statement. Switch is more suited for a large range of conditions.
  4. Most important. Using break will make you get out of the loop. Using continue will skip this loop and go to next iteration.

So now your code should look shorted and cleaner:)

class Numbers {
    public static void main (String args[]) {
        for (int i = 1; i <=30; i++){
            if(i % 3 == 0){
             continue;
            }
             System.out.println(i);
            }
        }
    }
}

Or you could go with shorter version:

for (int i = 1; i <=30; i++){
    if(i % 3 != 0){
       System.out.println(i);
    }
}
Beri
  • 11,470
  • 4
  • 35
  • 57
  • This snipplet will display: 1,2,4,5,7,8,10...29. So all numbers in given range that are n%3!=0 – Beri May 02 '15 at 06:36
1

Another short solution.

As we know that from 1 to 30 there are only 10 numbers divisible by 3, we make ten loops to print them all.

for (int i = 1; i <= 30; ++i) {
    System.out.printf("%d%n%d%n", i++, i++);
}

The idea is to print the two numbers before the one which is divisible by 3 and skip the one which is divisible.

  • the counter i starts at 1
  • the first %din System.out.printf prints current i (i=1) and increase it by 1 (i=2)
  • the second %din System.out.printf prints current i (i=2) and increase it by 1 (i=3)
  • the end condition of the for-loop increase i by 1 (i=4)
  • repeat till the end condition i <= 30 is false

edit A more readable version (as proposed by ajb)

for (int i = 1; i <= 30; i += 3) {
    System.out.printf("%d%n%d%n", i, i + 1);
}
SubOptimal
  • 22,518
  • 3
  • 53
  • 69
  • Aack. This kind of mucking with the loop index leads to unreadable code. A better way to express the same idea: `for (int i=1; i<=30; i+=3) { System.out.printf("%d%n%d%n", i, i+1); }` – ajb May 03 '15 at 04:11
  • @ajb Agree. I amend my answer and added your version. – SubOptimal May 03 '15 at 08:30
0

The code is OK - if i % 3 results in 0, nothing is printed. Since there are only two possiblities I would rewrite as if-statement:

if( ( i % 3 ) != 0 )
{
   System.out.println( i );
}

Is in my opinion better readable and conveys the intent more clearly.

More on the actual statement:

switch( i % 3 )
{
      case 0:
         //do nothing
       break; // leave switch - statement
      ...
}

The break is needed to leave the switch statement. So yes, it is necessary.

Mario The Spoon
  • 4,799
  • 1
  • 24
  • 36