我有一个字符串数组,其中包含要转换为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";
}
}
}
答案 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实施,您可以在该网站(右上角链接)上找到这些实施,并从中进行学习。