ユーザーからの入力の受信と検証を処理する「ConsoleSupport」クラスを使用しています。私が気づいた 1 つの問題は、最初にコンソール 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();
}
}