How to use Scanner to accept only valid int as input

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

提交回复
热议问题