How to use Scanner to accept only valid int as input

后端 未结 6 1454
梦谈多话
梦谈多话 2020-11-22 05:53

I\'m trying to make a small program more robust and I need some help with that.

Scanner kb = new Scanner(System.in);
int num1;
int num2 = 0;

System.out.prin         


        
6条回答
  •  Happy的楠姐
    2020-11-22 06:43

    Try this:

        public static void main(String[] args)
        {
            Pattern p = Pattern.compile("^\\d+$");
            Scanner kb = new Scanner(System.in);
            int num1;
            int num2 = 0;
            String temp;
            Matcher numberMatcher;
            System.out.print("Enter number 1: ");
            try
            {
                num1 = kb.nextInt();
            }
    
            catch (java.util.InputMismatchException e)
            {
                System.out.println("Invalid Input");
                //
                return;
            }
            while(num2

    You could try to parse the string into an int as well, but usually people try to avoid throwing exceptions.

    What I have done is that I have defined a regular expression that defines a number, \d means a numeric digit. The + sign means that there has to be one or more numeric digits. The extra \ in front of the \d is because in java, the \ is a special character, so it has to be escaped.

提交回复
热议问题