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.
case
Requires a Constant ExpressionNo. 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);
}
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);
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.
No, in Java you cannot do it. Use if
statement instead. Constructs similar to what you want exist in other languages like Scala.
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
.
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!");}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With