Else If is not working



else-if语句不起作用。告诉我。"语法错误,删除上令牌"如果"删除这个令牌"如果我摆脱了"如果"我猜。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 A­Z");
            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;
    }
}

您的else-if中有一个括号,而不是左括号。此外,您有一个分号而不是括号,并且缺少一个右括号。

此:

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 A­Z");
            guessed.add(goat); // Unreachable Code
            return currentPhrase.guessLetter(goat);
            return false;
        }

如果程序进入else If,您的代码:

  • 抛出异常(并且不继续执行块的内容)
  • 将山羊添加到猜测中(无法访问的代码)
  • return(无法访问的代码)
  • 再次返回(双重不可达代码)

认为你试图这样做:

    } else if (String.valueOf(play).matches("[A-Z]")) {
        throw new IllegalStateException(
                "the guess should be a letter from A­Z");
    }
    guessed.add(goat); // Unreachable Code
    return currentPhrase.guessLetter(goat);

但我不是很确定。

此外,如果你想在字母不在你需要的A-Z范围内时抛出异常:

else if (!String.valueOf(play).matches("[A-Z]")) {

当游戏与[A-Z]不匹配时。

最新更新