清除Java中不需要的输入
我使用的是一个“ConsoleSupport”类,它处理用户输入的接收和验证。我注意到的一个问题是,如果我首先在控制台UI中请求一个整数(菜单选项),然后请求几个字符串,那么第一个字符串将为空。可怕的换行符再次出现!在返回值之前,我在getType方法中使用了以下方法:清除Java中不需要的输入,java,input,newline,Java,Input,Newline,我使用的是一个“ConsoleSupport”类,它处理用户输入的接收和验证。我注意到的一个问题是,如果我首先在控制台UI中请求一个整数(菜单选项),然后请求几个字符串,那么第一个字符串将为空。可怕的换行符再次出现!在返回值之前,我在getType方法中使用了以下方法: if(in.hasNextLine()) in.nextLine(); 有没有人有其他更“优雅”的解决方案来处理不需要的输入 以下(缩写)类仅供参考 import java.util.Scanner; /** *
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();
}
}
只有在用户点击enter键后,才能读取
系统中的输入。因此,在扫描程序的缓冲区中,整数后面有一个额外的换行符。因此,当您调用Scanner.nextLine()
时,您将读取整数,但下次调用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.");
}
}
你不需要检查末端是否有多余的线,然后冲洗扫描仪