尝试将山羊添加到数组列表中。我在评论中写下了我的错误。 Arraylist 无法解析为类型。 和无法访问的代码。
● 如果已经猜到了该字符,则应抛出 IllegalArgumentException 并附有一条消息,说明该字母已被猜出
● 如果该字符不是来自 AZ 的字母(借用字母中的 if 代码 模型类下的构造函数第 6 步),它应该抛出一个 IllegalArgumentException 带有一条消息,指出猜测应该是一个字母 来自亚利桑那州
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);
}
public PhraseGameController(){
currentPhrase = new Phrase("This is only a test");
guessed = new ArrayList<Character>(); ///Arraylist could not be resolved to Type
}
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;
}
}
..
>
package edu.htc.java1.phrasegame.model; > > import java.util.ArrayList; > > public class Phrase { > // public String phrase; ArrayList<Letter> letters = new ArrayList<Letter>(); private String phrase; > > > public Phrase(String phrase) { phrase = phrase.toUpperCase(); //// > Problem for(char c : phrase.toCharArray()) { letters.add(new > Letter(c)); } this.phrase = phrase; } public void > setPhrase(String phrase) { this.phrase = phrase; } > > public String getPhrase() { return phrase; } > > public ArrayList<Letter> getLetters() { return letters; } > > public boolean guessLetter(char c) { > boolean foundLetter = false; > > // loop through your list of letters > for(Letter l : letters){ > // if list of letters contains same letter as the one you received then return true > if(l.getLetter() == c) { > l.unhide(); > foundLetter = true; > } > } > > // we did not find the letter, so we return false > return foundLetter; } }
最佳答案
else {String.valueOf(play).matches("[A-Z]");
这并没有按照您的想法进行。
这就是说,如果尚未猜测该值,则(始终)查看 play 是否匹配 A-Z
,忽略结果,然后(在下一行中)始终抛出 IllegalStateException
.
因此,无论此时发生什么,总会抛出 IllegalStateExcetpion,因此永远无法到达方法末尾的 return 语句。
您几乎肯定希望将上述代码包装在第二个 if 语句中,格式类似于:
else if(otherThingToCheck()) {
//Code to execute if otherThingToCheck() is true
}
关于java - 无法访问代码的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22968911/