你能在Android的switch-case中使用条件语句吗?

Rob*_*ert 5 java android switch-statement

在我的搜索中,我似乎无法找到一个直接的是或否.在Android中,有没有办法在case-switch中使用条件语句?例如,age是int值:

switch (age){
case (>79):
 // Do this stuff
 break;
case (>50):
 // Do this other stuff
break;
etc, etc
Run Code Online (Sandbox Code Playgroud)

我已经尝试了几种编码方式(完全在黑暗中拍摄)并出现编译器错误,我也尝试了嵌套的IF语句,但它不支持break,因此逻辑崩溃并最终还在嵌套中执行较低的ELSE代码.我觉得switch-case是我最好的选择,但我找不到一个正确的语法示例,我正在尝试做什么!任何帮助,将不胜感激.我找到的所有例子只是使用switch-case来做一些事情,比如它是1做这个,如果是2做那个,但没有制作100个案例陈述来检查年龄,我不知道怎么办这个.

Ell*_*sch 7

不,你不能这样做,

switch (age){
case (>79):
  // Do this stuff
  break;
case (>50):
  // Do this other stuff
  break;
}
Run Code Online (Sandbox Code Playgroud)

你需要一个ifelse,

if (age > 79) {
 // do this stuff.
} else if (age > 50) {
 // do this other stuff.
} // ...
Run Code Online (Sandbox Code Playgroud)


Wil*_*iem 6

这不可能.相反,尝试这种极简主义的方法

 age > 79 ? first_case_method() 
          : age > 50 ? second_case_method() 
          : age > 40 ? third_case_method() 
          : age > 30 ? fourth_case_method() 
          : age > 20 ? fifth_case_method()
          : ... 
          : default_case_method();
Run Code Online (Sandbox Code Playgroud)

  • 这与问题没有直接关系,即使通过它也可以被视为有效答案。请提供更多详细信息,因为问题与 switch 语句有关,而您的答案提供了 if-then-else 解决方案。 (2认同)