【发布时间】:2015-05-29 21:24:48
【问题描述】:
所以我有一个错误检测程序,如果当前单词(String cWrd)不包含在静态数组(作为参数传递)中,它应该检测“错误”。如果在数组中未找到该单词,则“找到的布尔值”保持为假,并且在一段时间内将 JLabel 设置为“错误类别”。 但是,即使 cWrd 不包含在数组中,该方法似乎也不会执行。
代码:
//Mistake method
public void mistake(String[] arr) {
int i = 0;
boolean found = false;
while (i < arr.length && found == false) {
if (arr[i].equals(cWrd)) {
found = true;
}
i++;
}
if (found == false) //The program never enters this if statement
{
lmid.setText("Wrong Category!");
try {
t1.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
编辑: 这是我正在测试的两个数组
String[] positive =
{"Happy","Beautiful","Wonderful","Generous","Loving","Supportive","Caring"};
String[] negative = {"Nasty","Gross","Horrible","Obnoxious","Mean","Disaster","Angry"};
这是将 cWrd = 设置为来自正负数组组合的随机单词的方法(ArrayList 未图示)
public void wordGen()
{
wchooser = rand.nextInt(words.length);
lmid.setText(" " + words[wchooser]);
cWrd = lmid.getText();
}
【问题讨论】:
-
将
if (found = false)更改为if (found == false) -
只需使用
if (found)或while (!found)。if (found == true)...while (found == false),这是多余的。 -
最好还是改成
if(!found) -
顺便说一句:
t1.sleep(100);不会在t1线程上休眠,而是在当前线程上休眠。这是为什么我们应该避免从引用而不是类调用静态方法的标准示例之一。简单来说t1.sleep(100);和Thread.sleep(100);是一样的。 -
我不确定您所说的 当前线程 是什么意思,因为
Thread.sleep会影响将执行此代码的线程(即当前线程)。如果你想暂停 other thread 那么你可能应该使用某种 volatile signal ,它将在那个线程中被检查。
标签: java arrays user-interface if-statement