0

i want to print the content in the catch block if an input mismatch occurs. i have written the code for the class Marathon whose object is created here. help me out

 import java.util.InputMismatchException;
 import java.util.Scanner;
 public class Main {

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);          
        Marathon m=new Marathon();
        System.out.print("Enter name: ");
        String name=sc.nextLine();
        System.out.print("Enter age: ");
        int age=sc.nextInt();
        System.out.print("Enter Gender: ");
        char gender=sc.next().charAt(0);
        System.out.print("Enter Contact no: ");
        long number=sc.nextLong();    
        try{
            m.setName(name);
            m.setAge(age);
            m.setGender(gender);
            m.setContactNo(number);
            System.out.println("Registered Successfully");
        }
        catch(InputMismatchException e){
          System.out.print("Invalid Input");
        }
    }   

1 Answers1

0

You need to catch the execptions that will be thrown from the input inside the try-catch block

public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);          
    Marathon m=new Marathon();
    System.out.print("Enter Contact no: ");        
    try{
        System.out.print("Enter name: ");
        m.setName(sc.nextLine());
        System.out.print("Enter age: ");
        m.setAge(sc.nextInt());
        System.out.print("Enter Gender: ");          
        m.setGender(sc.next().charAt(0));
        m.setContactNo(sc.nextLong());
        System.out.println("Registered Successfully");
    }
    catch(InputMismatchException e){
      System.out.print("Invalid Input");
  }
}
aookami
  • 53
  • 3