在Java中切换:是否可以在案例中包含条件? [英] Switches in Java: Can I include a condition in a case?

查看:40
本文介绍了在Java中切换:是否可以在案例中包含条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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

如果年龄为15岁,会发生什么?好吧,这给了我一个错误.所以我想知道案件中是否可以包含条件.例如,

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;

我可以使用if语句,但是我想知道是否可以通过开关来实现.

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

推荐答案

case 需要常量表达式

不.这是不可能的,因为 case必须是常量表达式 .但是您可以(如您所猜)使用 if .逻辑上, 20 (假设是法定年龄)以下的任何人都太年轻而无法开车.

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

或者

可以用 <代码>?:条件运算符(又称为三元表达式 note 有些人觉得三元法难以阅读),如

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

这篇关于在Java中切换:是否可以在案例中包含条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆