首页 > 解决方案 > 陷入Java电影猜谜游戏的逻辑(通过udacity)

问题描述

我正在Java上制作一个电影猜谜游戏(很像刽子手,但不包含简笔画之类的东西),它逐个字母地从用户那里获取输入。我被困在我想要输入的字母以替换电影标题中该字母的所有实例的位置。我的代码没有完全工作。稍后,我将应用阻止用户再次输入相同字母的逻辑。但目前我需要解决这个特定问题。有什么帮助吗?

这是我的游戏类中的游戏过程函数。

public void GameProcess(char[] dashedarray) {
        Scanner input = new Scanner(System.in);
        char guess;
        int i = 0;
        int spaces = 0;
        int correct = 0;
        int wrong = 0;
        boolean run = true;
        while (run) {
            if (dashedarray[i] == ' ') {
                spaces++;
                i++;
                continue;
            } else {
                System.out.println("Enter your guess.");
                guess = input.next().charAt(0);
                for (int j = 0; j < dashedarray.length; j++) {
                    if (dashedarray[j] != ' ') {
                        if (moviename.charAt(i) == guess) {
                            dashedarray[i] = guess;
                            correct++;
                        }
                        else if(moviename.charAt(j) == guess)  {
                            dashedarray[j] = guess;
                            correct++;
                        }
                        }
                        else
                        {
                            wrong++;
                        }
                    }
                i++;
                PrintArray(dashedarray);

                if (correct == (moviename.length() - spaces)) {
                    System.out.println("You have won.");
                    break;
                } else if (wrong == 10) {
                    System.out.println("You have lost.");
                    break;
                }
                System.out.println("The number of wrong guesses is " + wrong + ".");
            }
        } 

标签: javaarraysclassobjectlogic

解决方案


你根本不需要ispaces就是统计你的答案有多少个空格,这个不用猜。您应该在循环之外执行此操作。

Scanner input = new Scanner(System.in);
char guess;
int i = 0;
int spaces = 0;
int correct = 0;
int wrong = 0;
boolean run = true;

for (int i = 0; i < dashedarray.length; i++) {
    spaces++;        
}

while (run) {
    System.out.println("Enter your guess.");
    guess = input.next().charAt(0);

    boolean match = false;
    for (int j = 0; j < dashedarray.length; j++) {
        if (dashedarray[j] != ' ') {
            if(moviename.charAt(j) == guess)  {
                dashedarray[j] = guess;
                correct++;
                match = true;
            }
        }
    }

    // It matched nothing, this input is wrong.
    if (!match) {
        wrong++;
    }

    PrintArray(dashedarray);

    if (correct == (moviename.length() - spaces)) {
        System.out.println("You have won.");
        break;
    } else if (wrong == 10) {
        System.out.println("You have lost.");
        break;
    }
    System.out.println("The number of wrong guesses is " + wrong + ".");
}

推荐阅读