Switch without break(不间断切换)
问题描述
我有一些 switch 语句,如下所示.注意没有休息.Findbugs 仅在第二个 case 语句上报告错误.错误是:在一个案例落入下一个案例的地方找到了 Switch 语句.
I have some switch statement as shown below. Notice there is no break. Findbugs is reporting error on the second case statement only. The error is : Switch statement found where one case falls through to the next case.
switch(x) {
case 0:
// code
case 1:
// code
case 2:
// code
}
推荐答案
Findbugs 指出如果第一个有任何代码,从一个 case
跌到下一个通常不是一个好主意一个(尽管有时它可以起到很好的效果).所以当它看到第二个 case
并且没有 break
时,它会报告错误.
Findbugs is flagging up that falling through from one case
to the next is generally not a good idea if there's any code in the first one (although sometimes it can be used to good effect). So when it sees the second case
and no break
, it reports the error.
例如:
switch (foo) {
case 0:
doSomething();
case 1:
doSomethingElse();
default:
doSomeOtherThing();
}
这是完全有效的 Java,但它可能没有达到作者的意图:如果 foo
是 0
,所有三个doSomething
、doSomethingElse
和 doSomeOtherThing
函数运行(按此顺序).如果 foo
是 1
,则只有 doSomethingElse
和 doSomeOtherThing
运行.如果 foo
是任何其他值,则只有 doSomeOtherThing
运行.
This is perfectly valid Java, but it probably doesn't do what the author intended: If foo
is 0
, all three of the functions doSomething
, doSomethingElse
, and doSomeOtherThing
run (in that order). If foo
is 1
, only doSomethingElse
and doSomeOtherThing
run. If foo
is any other value, only doSomeOtherThing
runs.
相比之下:
switch (foo) {
case 0:
doSomething();
break;
case 1:
doSomethingElse();
break;
default:
doSomeOtherThing();
break;
}
这里只有一个函数会运行,具体取决于foo
的值.
Here, only one of the functions will run, depending on the value of foo
.
由于忘记 break
是一种常见的编码错误,Findbugs 等工具会为您标记出来.
Since it's a common coding error to forget the break
, tools like Findbugs flag it up for you.
有一个常见的用例,你有多个 case
语句在一行中 no 介入代码:
There's a common use-case where you have multiple case
statements in a row with no intervening code:
switch (foo) {
case 0:
case 1:
doSomething();
break;
case 2:
doSomethingElse();
break;
default:
doSomeOtherThing();
break;
}
如果 foo
是 0
or 1
doSomething>.大多数工具不会将此标记为可能的编码错误,因为在 case 1
之前的 case 0
中没有代码,这是一种相当常见的模式.
There, we want to call doSomething
if foo
is 0
or 1
. Most tools won't flag this up as a possible coding error, because there's no code in the case 0
prior to the case 1
and this is a fairly common pattern.
这篇关于不间断切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:不间断切换
基础教程推荐
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 降序排序:Java Map 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01