user5767743
user5767743

Reputation:

How to detect if first token of Scanner.next() is an Integer of a String?

Scanner scan = new Scanner(System.in);
scan.next(); //How to detects if the first token is an int; i.e (Integer.valueOf(scan) 
//will not throw InputMismatchException

I have overloaded methods

  void name(String name){
  System.out.println(name)
  }
  void age(int age){
  System.out.println(age)
  }

  void printAgeOrName(){
  System.out.println("Enter name or age");
  String data = scan.next();
 *if(first token of date is int){
  age(Integer.valueOf(date));
  }else{
  name(data);
  }
` }

scan.hastNextInt() only works for when more than one token is entered. I am yet to be aquinted with regex

Upvotes: 0

Views: 1146

Answers (3)

Faraz
Faraz

Reputation: 6275

int i;
while (scan.hasNext()) {
  if (scan.hasNextInt()) {
    i = scan.nextInt();
    System.out.println("int: " + i);
  //do whatever
  }
 //do whatever
}

Upvotes: 1

user5767743
user5767743

Reputation:

This is what I ended up doing, thanks to @João Gatto code.

 void printAgeOrName(){
      System.out.println("Enter name or age");
      String data = null;
    try{
      data = scan.next();
      age(Integer.valueOf(date)); // will throw NumberFormatException if data is not an integer
    }catch (NumberFormatException n){  // catch and assume data is a string
      name(data);
      }
` }

Upvotes: 1

The nextInt method will throw InputMismatchException if the next token does not match the Integer regular expression, or is out of range

Print "This is not an integer" when user put other than integer

Scanner sc=new Scanner(System.in);
try {
  System.out.println("Please input an integer");
  int usrInput=sc.nextInt();
  ...
} catch(InputMismatchException exception) {

  System.out.println("This is not an integer");
}

Upvotes: 0

Related Questions