0

ユーザーからの入力の受信と検証を処理する「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();
    }
}
4

1 に答える 1

1

からの入力System.inは、ユーザーが Enter キーを押すまで読み取ることができません。そのため、整数の後にスキャナのバッファに余分な改行があります。したがって、呼び出すScanner.nextInt()と整数がScanner.nextLine()読み取られますが、次に を呼び出すと、バッファ内の改行まで読み取られ、空白の文字列が返されます。

それに対処する1つの方法は、上記のように常に呼び出し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 に答える