如何限制用户扫描程序输入数据类型(java)?

时间:2014-07-27 15:52:05

标签: java java.util.scanner restriction

说,我希望用户只输入一个整数,而不是"培根",有没有办法将用户输入限制为整数(或其他数据类型),所以我不想得到除整数之外的任何错误和/或输入?

2 个答案:

答案 0 :(得分:2)

假设您的扫描仪名称为myScanner:

public static int checkMyInput () { 
    try {
        return myScanner.nextInt();
    } catch (InputMismatchException e ) {
         myScanner.next();
         System.out.println("bacon luff");
        return 0 ;
    }
}

然后你可以调用那个方法。

答案 1 :(得分:1)

这是一个功能齐全的例子:

import java.util.Scanner;

public class Temp {

    public static void main(String[] args) {
        Scanner inp = new Scanner(System.in);
        int num = 0;
        String input = "";
        String exit = "exit";
        boolean isStringNumber = true;//If the String is not Number

        System.out.println("NOTE: To exit, type the word exit and press enter key");

        while(true){

            System.out.println("\nPlease enter a number only...");
            input = inp.nextLine();

            if(input.equalsIgnoreCase(exit)){break;}

            isStringNumber = input.matches("[0-9]+");//Check if no digits in string

            if(isStringNumber == false){
                System.out.println("\nYou entered a non number " + input);
                System.out.println("Remove all non numbers from your input and try again !");
                continue;
            }else{
                num = Integer.parseInt(input);
                System.out.println("You entered " + num);
            }

        }

        System.out.println("Exiting program...");

    }

}