Java hang子手:检查给定字母是否在char数组内

时间:2019-06-23 03:39:36

标签: java arrays

我有一个字符串数组,其中包含要转换为char数组的单词。另外,我将用户输入作为字符串,然后将其转换为char并将其添加到数组。我正在尝试根据该单词检查用户输入的内容,以及它是否仅匹配println正确或不正确。我不确定如何编码。

private String[] wordsForGuessing = new String[] {"one", "david", 
                                         "storage", "unhelpful"};
private String ranWord = randomWord(wordsForGuessing);
private char[] convertRanWordToACharArray = ranWord.toCharArray();

private int MAX_SIZE = countsHowManyLettersAreInAWord(ranWord);
//adding three extra turns to guess
private char[] letter = new char[MAX_SIZE + 3];

private String guess;

//Check user input to see if the letter is in the word
private void checkUserInputToRanWord(char[] word, String guess)
{
    String message = "This is ";

    for(int i = 0; i < word.length; i++)
    {
        if(guess.charAt(0) == word[i])
        {
            message += " correct guess";
        }else{
            message += " incorrect guess";
        }
    }

}

1 个答案:

答案 0 :(得分:0)

已经有关于如何检查事物是否属于数组的问题的答案,例如:How do I determine whether an array contains a particular value in Java?

带有循环的一般模式是使用break;

在第一次比赛时离开循环
boolean found = false;
for (int i = 0; i < word.length; i++)
{
    if (guess.charAt(0) == word[i])
    {
        found = true;
        break;
    }
}
if (found) {
    ...
}

但是,现代的Java您可以使用流和anyMatch();将其减少为一行,就像链接的答案一样。

我还建议您查看Java上现有的Hangman实施,您可以在该网站(右上角链接)上找到这些实施,并从中进行学习。