卡在Java电影猜谜游戏的逻辑中(由udacity提供)

时间:2018-06-20 01:59:19

标签: java arrays class object logic

我正在Java上制作电影猜谜游戏(类似于hangman,但不包含简笔画和东西),该游戏可以逐个字母地接收用户的输入。我被困在希望输入的字母替换电影标题中该字母的所有实例的位置。我的代码无法完全正常工作。 稍后,我将应用阻止用户再次输入相同字母的逻辑。但是目前,我需要解决此特定问题。有帮助吗?

这是我游戏类中的游戏过程功能。

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 + ".");
            }
        } 

1 个答案:

答案 0 :(得分:0)

您根本不需要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 + ".");
}