-1

What can I do to detect string input as an error, where the user has to enter an int value? What is the condition I can use to detect whether the user has entered a string value?

Scanner input = new Scanner(System.in); 
int characterNum = input.nextInt();

do{

 if ((characterNum < 0)&&(characterNum > 12)){
 System.out.println("Invalid Input, Try again");

  }

 characterNum = input.nextInt();

 }while((characterNum < 0)&&(characterNum > 12));
sk3ptic
  • 1
  • 2
  • What I understood is, you are trying to get user input but you want to make sure it is a numeric value? – ElSheikh May 03 '18 at 07:45
  • 2
    Look at this https://stackoverflow.com/questions/6456219/java-checking-if-parseint-throws-exception – David May 03 '18 at 07:45
  • can you put your code to see how are you trying to do ?? – abby37 May 03 '18 at 07:46
  • @ElSheikh yes exactly – sk3ptic May 03 '18 at 07:46
  • @S.Liyanage check David's comment – ElSheikh May 03 '18 at 07:48
  • @abby37 This is the part(loop) which i used to validate the range of the input number. How can I add the string validation condition in the same loop? – sk3ptic May 03 '18 at 12:17
  • [nextInt](https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt()) from the docs, it won't accept the string and it will throw input mismatch exception. So why you want to put additional condition for string or I may be missing something in question ?? – abby37 May 03 '18 at 13:09

1 Answers1

-2

By Using instanceof :

Use "s instanceof String" , where s is variable entered by user to check wither it is String or not

Abhilash Arjaria
  • 142
  • 2
  • 10
  • If the OP takes a string as input, and they want to know if it is or is not parsable as an integer, `instanceof String` is obviously going to be true. If they try and take input as something other than a string, it will be false. Either way, it is not helpful. – khelwood May 03 '18 at 07:59