为什么我的程序要求一个符号两次而不是一次(忽略第一个符号)



这是一款简单的Hangman游戏:

public static void main(String[] args) {
    String[] words = {"writer", "that", "program"};
    int wordNumber = (int) (Math.random() * words.length);
    System.out.print("Enter a letter in word ");
    for (int i = 0; i < words[wordNumber].length(); i++)
        System.out.print('*');
    System.out.print(" > ");
    Scanner input = new Scanner(System.in);
    char letter;
    do {
        letter = input.nextLine().charAt(0);
        boolean asterisksInWord = false;
        String[] discoveredElements = new String[words[wordNumber].length()];
        int countOfTries = 0;
        int arrayCount = 0;
        int asteriskCount = 0;
        System.out.print("Enter a letter in word ");
        do {
            asterisksInWord = false;
            boolean contain;
            if (asteriskCount != 1) {
                asteriskCount = 0;
                for (char item : words[wordNumber].toCharArray()) {
                    contain = Arrays.asList(discoveredElements).contains(String.valueOf(item));
                    if (contain) {
                        System.out.print(item);
                    } else if (item == letter) {
                        System.out.print(item);
                        discoveredElements[arrayCount] = String.valueOf(item);
                        arrayCount++;
                    } else {
                        System.out.print('*');
                        asterisksInWord = true;
                        asteriskCount++;
                    }
                }
            }
            if (asterisksInWord) {
                System.out.print(" > ");
                letter = input.nextLine().charAt(0);
                if (asteriskCount != 1)
                    System.out.print("Enter a letter in word ");
            } else
                System.out.println("The word is " + words[wordNumber] +
                    " You missed " + (countOfTries + 2 - words[wordNumber].length()) + " time(s)");
            countOfTries++;
        } while (asterisksInWord);
        System.out.print("Do you want to guess another word? Enter y or n >");
    } while (input.nextLine().charAt(0) == 'y');
}

它运行的日志是

Enter a letter in word **** > t
Enter a letter in word t**t > h
Enter a letter in word th*t > a
The word is that You missed 0 time(s)
Do you want to guess another word? Enter y or n >y
y
Enter a letter in word **** > 

我的问题是,当问"你想猜另一个单词吗?"时,为什么它忽略了第一个符号"y"。

我试着用相同的do while条件创建一些测试程序,但他们并没有像那个程序那样要求2次字符。

程序要求您输入两次,因为您是这样编程的。在打印-"Do you want to guess another word? Enter y or n >"之后,您在while条件以及do之后的第一个语句中执行input.nextLine(),因此它要求输入两次。

也许您可以将问题Enter the letter in the word移动到内部do循环,而不是在if条件if (asterisksInWord) {中这样做。

此外,根据您当前的逻辑,它不会忽略您的第一个符号,这是决定是否退出循环的真正符号,下一个输入实际上是您的第一次猜测。

相关内容

  • 没有找到相关文章

最新更新