Java while循环用法未知
此页面用户必须在2个复选框中选择5次。所以我写了这个:Java while循环用法未知,java,netbeans,netbeans-6.9,Java,Netbeans,Netbeans 6.9,此页面用户必须在2个复选框中选择5次。所以我写了这个: if (box1a.isSelected() == true || box1b.isSelected() == true) { if (box2a.isSelected() == true || box2b.isSelected() == true) { if (box3a.isSelected() == true || box3b.isSelected() == tr
if (box1a.isSelected() == true || box1b.isSelected() == true) {
if (box2a.isSelected() == true || box2b.isSelected() == true) {
if (box3a.isSelected() == true || box3b.isSelected() == true) {
if (box4a.isSelected() == true || box4b.isSelected() == true) {
if (box5a.isSelected() == true || box5b.isSelected() == true) {
with some other things he does when it is true.
} else {
new Error("You must select an answer at all the questions");
}
然后,如果您没有选中顶部的复选框,他只会返回一个错误。然后克利里,我需要一个循环,但我不知道怎么做。我知道while循环是如何工作的,但不知道在这种情况下它会是什么样子。请帮忙
现在我也必须对文本字段做同样的处理,并且使用你们回答的相同方法是行不通的。有什么建议吗?在这种情况下,为什么不使用单选按钮(选中默认单选按钮)
if ((box1a.isSelected() == true || box1b.isSelected() == true) &&
(box2a.isSelected() == true || box2b.isSelected() == true) &&
(box3a.isSelected() == true || box3b.isSelected() == true) &&
(box4a.isSelected() == true || box4b.isSelected() == true) &&
(box5a.isSelected() == true || box5b.isSelected() == true)) {
//DO SOMETHING IF TRUE
}
else {
new Error("You must select an answer at all the questions");
}
无需循环^ ^一般策略如下:
bool flag = true;
do{
//search for input
if (/*the input is valid*/)
flag = false;
}while (flag);
但是如果你硬编码了这么多选项,你可能会有错误的设计。试试Jerome C.建议的单选按钮
if(!box1a.isSelected() && !box1b.isSelected()) {
// You must select an answer at all the questions
}
else if (box1a.isSelected() && box1b.isSelected() && box2a.isSelected() && box2b.isSelected() && box3a.isSelected() && box3b.isSelected() && box4a.isSelected() && box4b.isSelected() && box5a.isSelected() && box5b.isSelected()) {
// with some other things he does when it is true.
}
这里有几点需要注意
Error
这样的类名,因为它们通常用于真正的java.lang.Error
逻辑=
运算符您永远不应该使用==测试true。这是一种糟糕的风格,最好只使用
isSelected()
中的返回值,但不确定为什么要使用while循环。如果您认为用户必须“保持循环”,而您的条件(所有5个问题都已回答)不满足,那么这是不必要的。事件调度线程(EDT)将继续为您运行“循环”
另一方面,如果您正在寻找一种简洁的方法来验证所有复选框,那么您可以更改(假设)javax.swing.JCheckbox box1a;等,然后可以使用for循环迭代固定数组或数组列表。不需要while循环。如果不是你的问题,你只需要一个
,但是==true
是多余的。您可以将每一行简化为box1.isSelected()| | box2.isSelected()
,谢谢您的支持。但我总是会把它打两次,这并不是一件很麻烦的事,但要注意thanksuhm 2的复选框比一个收音机的复选框更方便用户,或者更美观、更美观,但是tnxwell。。。单选按钮用于此情况(一个所需选项),复选框用于多选。想一想人们知道什么,而不是你想什么,这样才能看得更清楚;)如果用户选中同一复选框组的两个值,如何管理数据?这是你想要的吗?不,我设定他只能检查一个。这是一个单选按钮,而不是复选框。我尝试使用相同的方法解决我稍后的问题,即文本字段不起作用。。。如果(answer1.getText().length()!=0)和(answer2.getText().length()!=0)尝试了(>0)任何建议?@Waldo King,if(answer1.getText().length()>0)和&(answer2.getText().length()>0)
如果两个文本框中都有文本,将返回true
。这就是你想要的吗?
if ((box1a.isSelected() || box1b.isSelected()) &&
(box2a.isSelected() || box2b.isSelected()) &&
(box3a.isSelected() || box3b.isSelected()) &&
(box4a.isSelected() || box4b.isSelected()) &&
(box5a.isSelected() || box5b.isSelected()))
{
//true stuff
}
else
{
new Error("You must select an answer at all the questions");
}