How to use Scanner to accept only valid int as input

后端 未结 6 1261
梦谈多话
梦谈多话 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条回答
  • 2020-11-22 06:27

    What you could do is also to take the next token as a String, converts this string to a char array and test that each character in the array is a digit.

    I think that's correct, if you don't want to deal with the exceptions.

    0 讨论(0)
  • 2020-11-22 06:31

    This should work:

    import java.util.Scanner;
    
    public class Test {
        public static void main(String... args) throws Throwable {
            Scanner kb = new Scanner(System.in);
    
            int num1;
            System.out.print("Enter number 1: ");
            while (true)
                try {
                    num1 = Integer.parseInt(kb.nextLine());
                    break;
                } catch (NumberFormatException nfe) {
                    System.out.print("Try again: ");
                }
    
            int num2;
            do {
                System.out.print("Enter number 2: ");
                while (true)
                    try {
                        num2 = Integer.parseInt(kb.nextLine());
                        break;
                    } catch (NumberFormatException nfe) {
                        System.out.print("Try again: ");
                    }
            } while (num2 < num1);
    
        }
    }
    
    0 讨论(0)
  • 2020-11-22 06:32
    1. the condition num2 < num1 should be num2 <= num1 if num2 has to be greater than num1
    2. not knowing what the kb object is, I'd read a String and then trying Integer.parseInt() and if you don't catch an exception then it's a number, if you do, read a new one, maybe by setting num2 to Integer.MIN_VALUE and using the same type of logic in your example.
    0 讨论(0)
  • 2020-11-22 06:42

    I see that Character.isDigit perfectly suits the need, since the input will be just one symbol. Of course we don't have any info about this kb object but just in case it's a java.util.Scanner instance, I'd also suggest using java.io.InputStreamReader for command line input. Here's an example:

    java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
    try {
      reader.read();
    }
    catch(Exception e) {
      e.printStackTrace();
    }
    reader.close();
    
    0 讨论(0)
  • 2020-11-22 06:43

    Use Scanner.hasNextInt():

    Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input.

    Here's a snippet to illustrate:

    Scanner sc = new Scanner(System.in);
    System.out.print("Enter number 1: ");
    while (!sc.hasNextInt()) sc.next();
    int num1 = sc.nextInt();
    int num2;
    System.out.print("Enter number 2: ");
    do {
        while (!sc.hasNextInt()) sc.next();
        num2 = sc.nextInt();
    } while (num2 < num1);
    System.out.println(num1 + " " + num2);
    

    You don't have to parseInt or worry about NumberFormatException. Note that since the hasNextXXX methods don't advance past any input, you may have to call next() if you want to skip past the "garbage", as shown above.

    Related questions

    • How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)
    0 讨论(0)
  • 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<num1)
            {
                System.out.print("Enter number 2: ");
                temp = kb.next();
                numberMatcher = p.matcher(temp);
                if (numberMatcher.matches())
                {
                    num2 = Integer.parseInt(temp);
                }
    
                else
                {
                    System.out.println("Invalid Number");
                }
            }
        }
    

    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.

    0 讨论(0)
提交回复
热议问题