你能在Android的switch-case中使用条件语句吗? [英] Can you use conditional statements in switch-case in Android?

查看:158
本文介绍了你能在Android的switch-case中使用条件语句吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的搜索中,我似乎无法直截了当地回答是或否。在Android中,有没有办法在case-switch中使用条件语句?例如,age为int值:

I can't seem to find a straight forward yes or no to this in my searching. In Android, is there a way to use a conditional statement in case-switch? For example, with age being an int value:

switch (age){
case (>79):
 // Do this stuff
 break;
case (>50):
 // Do this other stuff
break;
etc, etc

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

I've tried several ways to code this (completely shooting in the dark) and come up with compiler errors, and I've also tried a nested IF statement, but it doesn't support break so the logic breaks down and it ends up also executing ELSE code lower in the nesting. I feel like switch-case is my best bet but I can't find an example of the correct syntax for what I'm trying to do! Any help would be appreciated. All the examples I find just use switch-case for a few things like if it is a 1 do this, if it's a 2 do that, but without making 100 case statements to check against age, I'm not sure how else to work this.

推荐答案

没有。你不能这样做,

switch (age){
case (>79):
  // Do this stuff
  break;
case (>50):
  // Do this other stuff
  break;
}

如果 >和 else

if (age > 79) {
 // do this stuff.
} else if (age > 50) {
 // do this other stuff.
} // ...

这篇关于你能在Android的switch-case中使用条件语句吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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