-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();
  }

}

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. Commented Apr 13, 2021 at 23:51

1 Answer 1

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");
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.