How to use Scanner to accept only valid int as input

后端 未结 6 1481
梦谈多话
梦谈多话 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: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);
    
        }
    }
    

提交回复
热议问题