【问题标题】:Use method return in if-statement在 if 语句中使用方法返回
【发布时间】:2016-04-09 01:53:03
【问题描述】:

我正在为一个项目创建一个单词搜索游戏程序,并且想知道我想做的事情是否可行。下面是遵循我项目指导方针的 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 (
    }

}

【问题讨论】:

  • 您应该只为 isPuzzleWord 方法返回 true 或 false

标签: java if-statement return-value


【解决方案1】:

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

if (isPuzzleWord(guess,words) == null) 或任何你想测试的东西。

【讨论】:

  • 非常感谢!
【解决方案2】:

试试下面的 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的返回值为null,那么您可以提供您的反馈,否则意味着单词匹配,您可以继续游戏而无需进一步操作。

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-12
      • 2018-04-18
      • 2020-01-11
      • 2020-08-20
      • 2013-07-22
      • 2020-02-01
      • 2013-12-12
      相关资源
      最近更新 更多