0

我正在使用“ConsoleSupport”类来处理用户输入的接收和验证。我注意到的一个问题是,如果我首先在控制台 UI 中询问整数(菜单选项),然后询问几个字符串,第一个字符串将为空。可怕的换行符再次来袭!在返回值以使其工作之前,我在 getType 方法中使用了以下内容:

if(in.hasNextLine())
    in.nextLine();

有没有人有替代的、更“优雅”的解决方案来处理不想要的输入?

(缩写)类在下面供参考

import java.util.Scanner;

/**
 * This class will reliably and safely retrieve input from the user
 * without crashing. It can collect an integer, String and a couple of other
 * types which I have left out for brevity
 * 
 * @author thelionroars1337
 * @version 0.3 Tuesday 25 September 2012
 */
public class ConsoleSupport
{

    private static Scanner in = new Scanner(System.in);


    /** 
     * Prompts user for an integer, until it receives a valid entry
     * 
     * @param prompt The String used to prompt the user for an int input
     * @return The integer
     */
    public static int getInteger(String prompt)
    {
        String input = null;
        int integer = 0;
        boolean validInput = false;

        while(!validInput)
        {
            System.out.println(prompt);
            input = in.next();
            if(input.matches("(-?)(\\d+)"))
            {
                integer = Integer.parseInt(input);
                validInput = true;
            }
            else
            {
                validInput = false;
                System.out.println("Sorry, this input is incorrect! Please try again.");
            }
        }

        if(in.hasNextLine())
            in.nextLine(); // flush the Scanner

        return integer;
    } 


    /**
     * Prompts the user to enter a string, and returns the input
     * 
     * @param prompt The prompt to display
     * @return The inputted string
     */
    public static String getString(String prompt)
    { 
        System.out.println(prompt);
        return in.nextLine();
    }
}
4

1 回答 1

1

System.in在用户点击回车之前,无法读取来自的输入。正因为如此,扫描仪缓冲区中的整数之后有一个额外的换行符。因此,当您调用Scanner.nextInt()时读取整数,但下次调用时Scanner.nextLine(),您将读取缓冲区中的换行符,它将返回一个空白字符串。

处理它的一种方法是总是像上面那样调用nextLine()和使用。Integer.parseInt()您可能会跳过正则表达式匹配,而只是抓住NumberFormatException

    while(!validInput)
    {
        System.out.println(prompt);
        input = in.nextLine();
        try {
            integer = Integer.parseInt(input.trim());
            validInput = true;
        }
        catch(NumberFormatException nfe) {
            validInput = false;
            System.out.println("Sorry, this input is incorrect! Please try again.");
        }
    }

而且您无需检查末尾是否有多余的线并冲洗扫描仪。

于 2012-09-25T04:25:42.183 回答