-3

I need to write code where the program fails and throws an exception if the second input on a line is a String rather than an Integer. I am confused as to how to compare if the input is a string or an int and I am also struggling on how to use a try/catch statement.

import java.util.Scanner;
import java.util.InputMismatchException;

public class NameAgeChecker {
public static void main(String[] args) {
  Scanner scnr = new Scanner(System.in);

  String inputName;
  int age;
  
  inputName = scnr.next();
  while (!inputName.equals("-1")) {
     // FIXME: The following line will throw an InputMismatchException.
     //        Insert a try/catch statement to catch the exception.
     age = scnr.nextInt();
     System.out.println(inputName + " " + (age + 1));
     
     inputName = scnr.next();
  }

}

karina
  • 21
  • 1
  • 1
    You could `Integer.parseInt()` your input and if it succeeds is an int, otherwise it isn’t. Alternatively, you could use a regex. – Edwin Dalorzo Apr 13 '21 at 23:51

1 Answers1

3

Instead of

age = scnr.nextInt();

Try

try {
    age = scnr.nextInt();
    System.out.println(inputName + " " + (age + 1));
}
catch(InputMismatchException e) {
    System.out.println("Please enter a valid integer");
}
sorifiend
  • 4,546
  • 1
  • 25
  • 39
LuckyBandit74
  • 161
  • 1
  • 8