否则if语句不起作用。告诉我。 “语法错误,删除on标记”如果“删除此标记”如果我摆脱“if”我的guessed.add(山羊)是无法访问的。我评论了代码中的位置。我不知道该尝试什么。
package edu.htc.java1.phrasegame;
import edu.htc.java1.phrasegame.model.*;
import java.util.ArrayList;
public class PhraseGameController {
private Phrase currentPhrase;
private ArrayList<Character> guessed;
public boolean doPlayerGuess(Character play) {
Character goat = Character.toUpperCase(play);
if (guessed.contains(play)) {
throw new IllegalStateException("the letter was already guessed");
} else if (String.valueOf(play).matches("[A-Z]")) {
throw new IllegalStateException(
"the guess should be a letter from AZ");
guessed.add(goat); // Unreachable Code
return currentPhrase.guessLetter(goat);
return false;
}
}
public PhraseGameController() {
currentPhrase = new Phrase("This is only a test");
guessed = new ArrayList<Character>();
}
public Phrase getCurrentPhrase() {
return currentPhrase;
}
public void setCurrentPhrase(Phrase currentPhrase) {
this.currentPhrase = currentPhrase;
}
public void setGuessed(ArrayList<Character> guessed) {
this.guessed = guessed;
}
public ArrayList<Character> getGuessed() {
return guessed;
}
}
答案 0 :(得分:7)
如果您在其他地方有一个括号而不是左括号。 此外,您有一个分号而不是括号,并且缺少右括号。
这:
else if {String.valueOf(play).matches("[A-Z]");
应该是这样的:
else if (String.valueOf(play).matches("[A-Z]")) {
关于您的修改:
你有这个:
} else if (String.valueOf(play).matches("[A-Z]")) {
throw new IllegalStateException(
"the guess should be a letter from AZ");
guessed.add(goat); // Unreachable Code
return currentPhrase.guessLetter(goat);
return false;
}
如果程序进入else-if,你的代码:
我想你试图这样做:
} else if (String.valueOf(play).matches("[A-Z]")) {
throw new IllegalStateException(
"the guess should be a letter from AZ");
}
guessed.add(goat); // Unreachable Code
return currentPhrase.guessLetter(goat);
但我不太确定。
另外,如果你想在字母不在A-Z范围内时抛出异常,你需要:
else if (!String.valueOf(play).matches("[A-Z]")) {
播放时 匹配[A-Z]。