使用java.util.Scanner验证输入

时间:2010-06-17 06:20:58

标签: java validation java.util.scanner

6 个答案:

答案 0 :(得分:136)

答案 1 :(得分:3)

要检查字符串的字母,可以使用正则表达式,例如:

someString.matches("[A-F]");

为了检查数字并停止程序崩溃,我有一个非常简单的类,您可以在下面找到您可以定义所需值的范围。 Here

    public int readInt(String prompt, int min, int max)
    {
    Scanner scan = new Scanner(System.in);

    int number = 0;

    //Run once and loop until the input is within the specified range.
    do 
    {
        //Print users message.
        System.out.printf("\n%s > ", prompt);

        //Prevent string input crashing the program.
        while (!scan.hasNextInt()) 
        {
            System.out.printf("Input doesn't match specifications. Try again.");
            System.out.printf("\n%s > ", prompt);
            scan.next(); 
        }

        //Set the number.
        number = scan.nextInt();

        //If the number is outside range print an error message.
        if (number < min || number > max)
            System.out.printf("Input doesn't match specifications. Try again.");

    } while (number < min || number > max);

    return number;
}

答案 2 :(得分:3)

这是一种极简主义的做法。

System.out.print("Please enter an integer: ");
while(!scan.hasNextInt()) scan.next();
int demoInt = scan.nextInt();

答案 3 :(得分:1)

答案 4 :(得分:0)

答案 5 :(得分:0)

我所尝试的是,首先我取整数输入并检查其是否为负数,如果其为负则再次接受输入

Scanner s=new Scanner(System.in);

    int a=s.nextInt();
    while(a<0)
    {
    System.out.println("please provide non negative integer input ");
    a=s.nextInt();
    }
    System.out.println("the non negative integer input is "+a);

在这里,您需要首先获取字符输入并检查用户是否给出了字符,如果不是再次接受字符输入

    char ch = s.findInLine(".").charAt(0);
    while(!Charcter.isLetter(ch))
    {
    System.out.println("please provide a character input ");
    ch=s.findInLine(".").charAt(0);
    }
    System.out.println("the character  input is "+ch);