我想在运行捕捉块时打印无效的输入,但它没有发生。

问题描述 投票:0回答:1

我想在输入不匹配的情况下,在捕捉区块中打印内容,我为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");
        }
    }   
java exception error-handling inputmismatchexception
1个回答
0
投票

你需要捕获将从输入中抛出的执行程序。里面 屡试不爽

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

0
投票

你需要把对Scanner方法的所有调用都放在像 nextInt 在尝试块内。

否则,异常就会在 try 块之前被抛出,因此你的 catch 块将永远不会被运行。您当前的情况永远不会触发 InputMismatchException,但如果 sc.nextInt()在捕获块之前,如果失败了,InputMismatchException将保持未处理状态。

        try{
          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();
          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");
        }
© www.soinside.com 2019 - 2024. All rights reserved.