12

Here is my code:

switch(age) {
    case 10:
        System.out.println("You are too young to drive.");
        break;
    case 20:
        System.out.println("You can drive!");
        break;
    default:
        System.out.println("Error");
}

What happens if the age is 15? Well, it gives me an error. So I was wondering if it's possible to include a condition within the case. For example,

case (age>=10 && age<=20):
   System.out.println("You're still too young to drive...");
   break;

I could use an if statement, but I'm wondering if this is possible with a switch.

Will
  • 24,082
  • 14
  • 97
  • 108
Code123
  • 325
  • 2
  • 3
  • 11
  • One can use anythingy inside `case` block, though more appropriate will be to use `case 10: to case 19:` and leave all blank with no break, except for the last one, with the statement `System.out.println("You're still too young to drive...");` and a `break;` to terminate or you can simply provide a `default:` label inside `switch` block, where you can specify the desired message :-) – nIcE cOw Jul 19 '15 at 03:50
  • http://stackoverflow.com/q/10873590/758280 – Jeffrey Jul 19 '15 at 04:17
  • Note that the result of the case is a Boolean so unless age is also Boolean then that doesn't even make sense. Java creates a jump table of constants from each case, then compares the switch against each value until first match then jumps there. This is why Java requires constness in case expressions. Basically can the case value be determined without execution (at compile time) ? If it can't then don't use it in a case. – ydobonebi Jul 19 '15 at 07:03

5 Answers5

12

case Requires a Constant Expression

No. It's not possible because a case must be a constant expression. But you could (as you guessed) use an if. Logically, anyone under 20 (assuming that's the legal age) is too young to drive.

final int drivingAge = 20;
if (age < drivingAge) {
    System.out.printf("%d is too young to drive...%n", age);
} else {
    System.out.printf("%d is old enough to drive.%n", age);
}

Alternatively

That could be written with ? : conditional operator (aka a ternary expression; note some people find the ternary difficult to read) like

final int drivingAge = 20;
System.out.printf(age < drivingAge ? "%d is too young to drive...%n"
        : "%d is old enough to drive.%n", age);
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • 5
    @Will: seems harsh to downvote somebody for something that's 1) a style preference and 2) an add-on rather than a core part of the answer.granted in many cases it's better to be narrower in scope so as to avoid attracting negative attention for non-core material. Note in this case the conditional expression is DRYer. – Nathan Hughes Jul 19 '15 at 04:02
  • @Will that is your subjective opinion. I find the ternary operator readable and I think that short **and expressive** code is better than long and unnecessarily verbose code (that is my subjective opinion)! – assylias Jul 19 '15 at 07:17
  • Anyhow, I've removed the downvote, since you added a note about some people finding it hard to read. Wasn't intending to argue here. – Will Jul 19 '15 at 07:51
6

Because of fall-through you can do this:

switch(age){
    case 10:  
    case 11:
    case 12:
    case 13:
    case 14:
    case 15:
    case 16:
    case 17:
    case 18:
    case 19:
        System.out.println("You are too young to drive.");
        break;  
    case 20:
        System.out.println("You can drive!");
        break;
    default:
        System.out.println("Error");
}

It is a little more code but it accomplishes the same thing.

MrMadsen
  • 2,713
  • 3
  • 22
  • 31
4

No, in Java you cannot do it. Use if statement instead. Constructs similar to what you want exist in other languages like Scala.

Community
  • 1
  • 1
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
3

You can't do this in Java. A switch jumps to the case that matches the value you're switching on. You can't use expressions of age inside the case. However, you can use something called a "fallthrough" (see here and search for "fall through").

So, for your example, you could do something like:

switch(age)
{
    case 10:
    case 11:
    case 12:
    case 13:
    case 14:
    case 15:
    case 16:
    case 17:
    case 18:
    case 19:
        System.out.println("You are too young to drive.");
        break;

    case 20:
    case 21:
        System.out.println("You can drive!");
        break;

    default:
        System.out.println("Error");
 }

However, your problem is best solved with an if.

Will
  • 24,082
  • 14
  • 97
  • 108
2

Sadly, it's not possible in Java. You'll have to resort to using if-else statements.You can try this, which is very repetitive.

  switch(age){ 
    case 10: case 11: case 12: case 13: case 14: case 15:
    //And So on
    System.out.println("You are too young to drive.");
        break;
    case 20:
        System.out.println("You can drive!");
        break;
    default:
        System.out.println("Error");
    }

Try if statement

   public void canDrive(int age){

   if(age <= 19){
       System.out.println("You are too young to drive.")
   }
   else{
       System.out.println("You can drive!");}
   }