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

时间:2015-06-30 14:49:14

标签: java user-input

这是简单的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 **** > 

我的问题是为什么它忽略了第一个符号&#39; y&#39;当问及#34;你想猜另一个词吗?&#34;。

我尝试使用相同的do-while条件创建一些测试程序,但他们不会像该程序那样要求2次字符。

1 个答案:

答案 0 :(得分:2)

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

也许您可以将问题Enter the letter in the word移到内部do循环,而不是在if条件if (asterisksInWord) {中执行此操作。

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