我正在使用“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();
}
}