我写了这段代码并且它的工作,但我似乎找不到一种更容易编写它的方法。现在,我正在指定所有可能的情况并为其添加功能。如果我只使用两个布尔变量(状态 1 和状态 2),就像下面的代码一样,它是可行的。但是如果我使用超过 2 个变量,我需要编写的代码太多了。
while (!status1 || !status2) {
if (!status1 && !status2) {
jTextField1.setForeground(Color.red);
jTextField2.setForeground(Color.red);
break;
} else if (!status1 && status2) {
jTextField1.setForeground(Color.red);
break;
} else if (status1 && !status2) {
jTextField2.setForeground(Color.red);
break;
}
基本上我想要实现的是编写类似于下面的代码的东西(没有指定所有可能的情况)。我测试了这段代码,但它只执行第一个 if 语句,而不执行其他语句。
我做错了什么?我希望它遍历所有 if 语句。
while (!status1 || !status2) {
if (!status1 {
jTextField1.setForeground(Color.red);
break;
} else if (!status2) {
jTextField2.setForeground(Color.red);
break;
}
while (!status1 || !status2 /* || !status3 || and so on*/) {
boolean do_break=false;
if (!status1) {
jTextField1.setForeground(Color.red);
do_break=true;
}
if (!status2) {
jTextField2.setForeground(Color.red);
do_break=true;
}
/* if (!status3) {
jTextField3.setForeground(Color.red);
do_break=true;
}*/
if(do_break) break;
here_the_part_that_you_omitted_from_the_question();//...
}
请澄清是否有您没有告诉我们的循环体。
其他就是你的问题。中断也不正确。
if (!status1) {
jTextField1.setForeground(Color.red);
}
if (!status2) {
jTextField2.setForeground(Color.red);
}
不明白为什么要使用 while
循环。这样的事情呢?
Color color1 = Color.red;
Color color2 = Color.red;
if (status1) {
color1 = 0;
}
if (status2) {
color2 = 0;
}
jTextField1.setForeground(color1);
jTextField2.setForeground(color2);
这是因为您在"while"语句中编写的语句与第一个"if"语句相同。如果你写
而(真)
相反,它应该有效。
这是简化的等效代码您的代码:
while (!status1 || !status2) {
if (!status1 && !status2) {
jTextField1.setForeground(Color.red);
jTextField2.setForeground(Color.red);
break;
} else if (!status1 && status2) {
jTextField1.setForeground(Color.red);
break;
} else if (status1 && !status2) {
jTextField2.setForeground(Color.red);
break;
}
}
在上面的代码中,根本不需要最后一个"如果"! 由于我们在 while 循环中,肯定有两个中至少有一个是错误的,如果控制来到这里,上面的所有"如果"都必须失败! 在这种情况下,这个 if 条件永远不会失败!
相同的结果,但很简单:尝试一下!
while (!status1 || !status2) {
if (status1) { //equivalent to (status1 && !status2)
jTextField2.setForeground(Color.red);
break;
} else if(status2){ //equivalent to (!status1 && status2)
jTextField1.setForeground(Color.red);
break;
}
jTextField2.setForeground(Color.red);
jTextField1.setForeground(Color.red);
break;
}