我的if语句表现得很奇怪,而不是仅在错误大于6时才打印,而是每次都不断打印“死”。关于为什么的任何想法?我已经更新了代码,以便您可以更好地理解我的逻辑。
int j = 0;
String line = "";
for(j = 0; j<64; j++) {
wordLength[j] = wordList[j].length();//gets length of words in wordList
}//end for
int f = 2;//change num to change level
int m = 0;
//creates line first then put into .setText
while(m<wordLength[f]) {
line += "__ ";
m++;
}//end for
jlLines.setText(line);
tf.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {//when enter key pressed
JTextField tf = (JTextField)e.getSource();
letter = tf.getText();
jlLetsUsed.setText(jlLetsUsed.getText() + letter + " ");//sets jlabel text to users entered letter
char[] jlabelText = jlLines.getText().toCharArray();//converts string to character array (array length is length of string)
char userEnteredChar = letter.charAt(0);
int wrong = 0;
int level = 2;//change num to change level
int i = 0;
for(i = 0; i<wordList[level].length(); i++){
if(wordList[level].charAt(i) == userEnteredChar){
jlabelText[3 * i] = ' ';
jlabelText[3 * i + 1] = userEnteredChar;
jlLines.setText(String.valueOf(jlabelText));
}else{
wrong++;
System.out.println(wrong);
}if(wrong >= 6){
System.out.println("dead");
break;
}
}//end for
}//end actionPerformed method
最佳答案
显然wrong
始终> =6。一种可能性是level
大于1个字符,因此包含检查始终为false。即使是“正确”的猜测也总是“错误”的。
更有可能的可能性是,因为递增wrong
的检查在循环内,所以任何时候wordList[level]
的长度为6个或更多字符且不包含letter
,wrong
将会递增6次或更多次。
您可能应该将检查放在循环之外。
for(int i = 0; i<wordList[level].length(); i++){
if(wordList[level].charAt(i) == userEnteredChar){
jlabelText[3 * i] = ' ';
jlabelText[3 * i + 1] = userEnteredChar;
jlLines.setText(String.valueOf(jlabelText));
}
}
if(!wordList[level].contains(letter)){
wrong++;
}
if(wrong>=6){
System.out.println("dead");
}
顺便说一句,这里的一个明显建议是,如果您正在检查
contains
,则最好先进行检查,如果contains
为假,则以某种方式跳过“显示”循环。看来
wrong
应该应该是某个字段。如图所示,我已将其声明为ActionListener上的字段。不要将其放在ActionListener上,而应该放在其他地方,最好放在包含类上。我看不到别的地方,这可能一开始就可以工作。关键是要在actionPerformed中的单个猜测之外跟踪“错误”的猜测。这意味着您必须在方法范围之外的某个地方声明它。tf.addActionListener(new ActionListener() {
int wrong;
@Override
public void actionPerformed(ActionEvent e) {
JTextField tf = (JTextField)e.getSource();
char userEntry = tf.getText().charAt(0);
jlLetsUsed.setText(jlLetsUsed.getText() + userEntry + " ");
int level = 2;
if (!wordList[level].contains(String.valueOf(userEntry))) {
wrong++;
if (wrong >= 6) {
System.out.println("dead");
}
return;
}
char[] jlabelText = jlLines.getText().toCharArray();
for (int i = 0; i < wordList[level].length(); i++) {
if (wordList[level].charAt(i) == userEntry) {
jlabelText[3 * i] = ' ';
jlabelText[3 * i + 1] = userEntry;
}
}
jlLines.setText(String.valueOf(jlabelText));
}
});