为扫雷程序循环打印 2 个错误而不是 1 个错误

Loop printing 2 errors instead of 1 for minesweeper

您将在下面找到方法规范以及我为匹配这些而编写的方法:

/**
 * This method prompts the user for a number, verifies that it is between min
 * and max, inclusive, before returning the number.  
 * 
 * If the number entered is not between min and max then the user is shown 
 * an error message and given another opportunity to enter a number.
 * If min is 1 and max is 5 the error message is:
 *      Expected a number from 1 to 5.  
 * 
 * If the user enters characters, words or anything other than a valid int then 
 * the user is shown the same message.  The entering of characters other
 * than a valid int is detected using Scanner's methods (hasNextInt) and
 * does not use exception handling.
 * 
 * Do not use constants in this method, only use the min and max passed
 * in parameters for all comparisons and messages.
 * Do not create an instance of Scanner in this method, pass the reference
 * to the Scanner in main, to this method.
 * The entire prompt should be passed in and printed out.
 *
 * @param in  The reference to the instance of Scanner created in main.
 * @param prompt  The text prompt that is shown once to the user.
 * @param min  The minimum value that the user must enter.
 * @param max  The maximum value that the user must enter.
 * @return The integer that the user entered that is between min and max, 
 *          inclusive.
 */

public static int promptUser(Scanner in, String prompt, int min, int max) {
    //initialize variables
    Integer userInput = 0;
    boolean userInteger = false;
    System.out.print(prompt);//prompts the user for input
    userInteger = in.hasNextInt();
    while (userInteger == false) {
            System.out.println("Expected a number from " + min + " to " + max +".");     
        in.nextLine();
        userInteger = in.hasNextInt();
    }

    while (userInteger == true) {
        userInput = in.nextInt();
        while (userInput > max || userInput < min) {
            System.out.println("Expected a number from " + min + " to " + max +".");
            in.nextLine();
            userInteger = in.hasNextInt();

            while (userInteger == false) {
                System.out.println("Expected a number from " + min + " to " + max +".");
                in.nextLine();
                userInteger = in.hasNextInt();

            }
            userInput = in.nextInt();                   
        }
        userInteger = false;
   }
   //userInteger = false; 
   return userInput; //FIXME
}

不幸的是,当我尝试使用以下值进行测试时: 4个 4个 5个 4个 哟 哟哟

当我输入 yo yo 时,我打印了两个错误,而不是 1 个。我知道我正在打印相同的打印语句两次,它是 while (userInteger = false) 循环下的打印语句。关于如何解决这个问题有什么想法吗?

当您在单个请求中键入 "yo yo" 时,Java 会将其解释为 "yo yo" 的单个字符串,而不是 2 个不同的字符串 "yo" 和 "yo".

如果您想要 2 条不同的错误消息,您需要每次输入一条 "yo"。

当您将 "yo yo" 作为输入时会发生这种情况。 Scanner.nextInt() 将第一个 "yo" 作为输入并打印错误消息,第二个 "yo" 保留在输入缓冲区中。 当它第二次调用 .nextInt() 时,它接收缓冲区中的第二个 "yo",并打印出另一个错误输出。

您可能会重新考虑使用 Scanner.nextLine() 然后解析输入而不是简单地使用 Scanner.nextInt()。

希望对您有所帮助。