Switching to Java: can I include a condition in case?

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 age is 15? Well, that gives me an error. So I was wondering if the condition could be included in this case. For instance,

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.

+4
source share
5 answers

case Constant expression required

No. This is not possible because it casemust be a constant expression . But you could (you guessed it) use it if. Logically, anyone who is under 20(assuming legal age) is too young to move.

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);
}

As an alternative

? : (aka , , , ),

final int drivingAge = 20;
System.out.printf(age < drivingAge ? "%d is too young to drive...%n"
        : "%d is old enough to drive.%n", age);
+7

, Java . if. , , , Scala.

+3

- :

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");
}

, .

+2

Java. case, . age case. -, "" (. "" ).

, - :

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");
 }

if.

+1

, Java. if-else. , .

  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");
    }

,

   public void canDrive(int age){

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

Source: https://habr.com/ru/post/1598552/


All Articles