How to use Scanner to accept only valid int as input

后端 未结 6 1266
梦谈多话
梦谈多话 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: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.

提交回复
热议问题