【问题标题】:i want to print invalid input when the catch block is run but it is not happening.Please help me out我想在运行 catch 块时打印无效输入,但它没有发生。请帮帮我
【发布时间】:2020-04-24 18:59:58
【问题描述】:

如果发生输入不匹配,我想打印 catch 块中的内容。我已经为在此处创建对象的 Marathon 类编写了代码。帮帮我

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

【问题讨论】:

  • 您的 try 块在扫描内容之后

标签: java exception error-handling inputmismatchexception


【解决方案1】:

您需要捕获将从输入内部try-catch块

抛出的异常
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");
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-09
    相关资源
    最近更新 更多