【发布时间】:2018-10-09 05:23:56
【问题描述】:
我的activity 上有 3 个checkboxes。我需要检查checkbox(clicked/unclecked) 的状态,并根据此结果执行特定操作。
我在这项工作中的逻辑如下:
if(Check1.isCheked) {
//some action
} else if(Check2.isCheked) {
//some action
} else if (Check3.isCheked) {
//some action
} else if ((Check1.isCheked) && (Check2.isCheked)) {
//some action
} else if ((Check1.isCheked) && (Check3.isCheked)) {
//some action
} // etc.
如果有一些更合理的方法,例如,因为我有 9 个checkboxes 并且为了他们的验证,我需要 509 个条件?
我的代码中这种情况的一个具体例子(这是我写的):
if (some_variable == 1) {
Intent intent = new Intent(this, activity.class);
intent.putExtra("1", mCheck1.isChecked());
intent.putExtra("2", (mCheck1.isChecked()) && (mCheck2.isChecked()));
//and other 507 variants
startActivity(intent);
} else if (some_variable == 2) {
Intent intent1 = new Intent(this, activity.class);
intent.putExtra("3", mCheck1.isChecked());
intent.putExtra("4", (mCheck1.isChecked()) && (mCheck2.isChecked()));
//and other 507 variants
startActivity(intent1);
}
在接下来的activity 中得到这个检查结果:
Boolean check1 = getIntent().getExtras().getBoolean("1");
Boolean check2 = getIntent().getExtras().getBoolean("2");
Boolean check3 = getIntent().getExtras().getBoolean("3");
Boolean check4 = getIntent().getExtras().getBoolean("4");
然后我开始 for 循环来检查这个结果:
if(check1) {
//query the database
} else if (check2) {
//query the database
} else if...
【问题讨论】:
-
条件是否总是检查
isChecked还是有时会有所不同? -
不,只检查
isCheked@Aominè -
您绝对可以创建一种方法来帮助减少
&&条件,但我想不出避免if、else if等的方法。 -
if块中每个if、else if是否有相似之处? -
我也想不通)@Aominè 所以我写了所有的 509 条件,但在这种情况下真的都是这样吗..
标签: java loops for-loop if-statement while-loop