java - 具有 int 范围的 switch 语句 [英] java - switch statement with range of int

查看:32
本文介绍了java - 具有 int 范围的 switch 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 switch 语句来检查一系列数字我发现一些地方说类似case 1...5case (score >= 120) &&(score <=125) 会起作用,但我只是以某种方式不断出错.

I want to use a switch statement to check a range of numbers I have found a few places saying something like case 1...5 or case (score >= 120) && (score <=125) would work but I just somehow keep on getting errors.

我想要的是,如果数字在 1600-1699 之间,那就做点什么.

What I want is if the number is between 1600-1699 then do something.

我可以做 if 语句,但如果可能的话,我想是时候开始使用 switch 了.

I can do if statements but figured it's time to start using switch if possible.

推荐答案

在JVM层面上,switch语句与if语句有着本质的区别.

On the JVM level switch statement is fundamentally different from if statements.

Switch 是关于必须在编译时全部指定的编译时常量,以便 javac 编译器生成高效的字节码.

Switch is about compile time constants that have to be all specified at compile time, so that javac compiler produces efficient bytecode.

在 Java 中 switch 语句不支持范围. 您必须指定所有值(您可能会利用这种情况)和 default案例.其他任何事情都必须由 if 语句来处理.

In Java switch statement does not support ranges. You have to specify all the values (you might take advantage of falling through the cases) and default case. Anything else has to be handled by if statements.

这篇关于java - 具有 int 范围的 switch 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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