Java Switch语句 [英] Java Switch Statement
问题描述
当我尝试处理特殊情况时,我遇到使用switch语句的问题。
例如,
我有3个案例:A,B,C。
I have a problem using switch statement when I tried to deal with a special situation. For example, I have 3 cases: A, B, C.
- 对于A,我想要do statement_1和statement_3。
- 代表B,我想做声明_2和声明_3。
- 代表C,我想什么都不做
如果我使用if-else语句,它将如下所示:
if I use if-else statement, it will look like the following:
if ( not C){
do statement_3
if B
do statement 2
else if A
do statement 1
}
如果我想使用switch语句来做同样的事情我有一些麻烦。
If I want to use switch statement to do the same thing, I have some trouble.
switch (variable){
case A: do statement_1
case B: do statement_2
// how to do statement 3 here?
}
我试图避免重复的代码。所以我在想如何使代码尽可能简单。
I am trying to avoid the duplicated codes. So I am thinking that how to make the codes as simple as I can.
更新1:
-
让我的代码/问题更加清晰,我只想让我的代码
尽可能简单/清晰,这就是我想要的原因使用switch语句
而不是if-else。另外,我听说switch语句通常比if-else快
。 (我不是100%肯定)。
to make my codes/question more clear, I just want to make my codes as simple/clear as I can, that is why I want to use switch statement instead of if-else. Also, I heard that switch-statement is usually faster than if-else. (I am not 100% sure though).
我想使用switch-case,因为案例A,B,C是枚举类型。他们
不变。对此感到抱歉。
I want to use switch-case because Case A, B, C are enum type. they are not variable. Sorry about the confusion.
每个语句超过10行代码。这就是为什么我不想做以下事情:
each statements are more than 10 lines of codes. That is why I do not want to do the followings:
switch (enum variable) {
case A:
statement1
statement3
break;
case B:
statement2
statement3
break;
}
推荐答案
我建议准确定义应该执行的staments:
i would recommend to define exactly what staments should be executed:
switch (variable){
case A:
statement_1();
statement_3();
break;
case B:
statement_2();
statement_3();
break;
}
for Update-3:
为这10行创建方法:
public void statement_1() {
//your 10 lines of code
}
如果你一直在执行statement_3 ,除了案例C,你可以在编写if / else-blocks时使用它们。
if you're always executing statement_3, except for case C you can go with if/else-blocks as you wrote them.
但我的诚实看法:
确切定义了必须是什么如果您有少量案件,在这种情况下完成。
它更容易为其他人阅读
but in my honest opinion: define EXACTLY what has to be done in which case if you have a small amount of cases. it is easier to read for others
这篇关于Java Switch语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!