在if语句中使用方法return



我正在为一个项目创建一个单词搜索游戏程序,想知道我想做的事情是否可行。下面是遵循我项目指导原则的isPuzzleWord方法,即如果单词正确,则必须从数组中返回单词类对象,如果单词不正确,则返回null。我的isPuzzleWord方法运行良好。

public static Word isPuzzleWord (String guess, Word[] words) {
    for(int i = 0; i < words.length; i++) {
        if(words[i].getWord().equals(guess)) {
            return words[i];
        }
    }
    return null;
}

我的问题是,我如何将这两个回答合并到if语句中,以便在猜测正确的情况下继续游戏,或者在猜测错误的情况下向用户提供反馈。

    public static void playGame(Scanner console, String title, Word[] words, char[][] puzzle) {
    System.out.println("");
    System.out.println("See how many of the 10 hidden words you can find");
    for (int i = 1; i <= 10; i++) {
        displayPuzzle(title, puzzle);
        System.out.print("Word " + i + ": ");
        String guess = console.next().toUpperCase();        
        isPuzzleWord(guess,words);
        if (
    }
}

您只需将要调用的函数放入if子句:

if (isPuzzleWord(guess,words) == null)或您想要测试的任何内容。

尝试以下if-else函数:

    if (isPuzzleWord(guess, words) == null){
        System.out.println("Your Feedback"); //this could be your feedback or anything you want it to do
    }

如果isPuzzleWord的返回为空,那么您可以提供反馈,否则这意味着单词匹配,您可以继续播放,而无需采取进一步行动。

您可以将返回单词的引用存储在if语句之后使用。

Word word = isPuzzleWord(guess,words);   
if (word == null) {
   System.out.println("its not a Puzzle Word");
} else {
   //you could access `word` here
}

最新更新