InputMismatchException不能与Integer.parseInt一起使用(args [0]);比如何在没有扫描仪的情况下让异常工作

时间:2018-04-24 05:26:43

标签: java

因此,如果用户输入age作为fish而不是整数,则InputMismatchException会输出“输入中的错误输入数字”。 或者如果用户没有在cmd(命令行)中输入任何内容,而不是在ArrayIndexOutOfBoundsException中输入“命令行上没有足够的参数”

Fuuthermore不应使用扫描仪。而age = Integer.parseInt(args [0]);必须用于将年龄从字符转换为整数

修改Question中的程序,以便在程序运行时从命令行获取用户的年龄。如果用户未在命令行上输入数字或在输入中出错,则程序应处理问题。

以下是代码:

 public class age {

public static void main(String args[]){
    int age = 0;




     // try   
    try{
       // convert age from character to integer 
       age = Integer.parseInt( args [0]) ;

       // check input age value
       // if ueser inputs age less or equal to 12
        if(age<= 12)
        System.out.println("You are very young");
        // if user enters age larger than 12 and less than 20
         if(age > 12 && Age < 20)
            System.out.println("You are a teen");
        // if user enters age larger than 20
       if (age > 20)
            System.out.println("wow" +Age+" is very old");
    }
    catch(InputMismatchException e){
       System.out.println("Error in the input enter a number");
    }
 catch ( ArrayIndexOutOfBoundsException exception0) {System.out.println   ("Not enough arguments on the command line" ) ; }
  }   
}   

1 个答案:

答案 0 :(得分:0)

因此,您希望捕获输入不是数字时引发的异常。由于您使用的是Integer.parseInt(String s),因此抛出的省略号为NumberFormatException。 (参见JavaDoc for Integer.parseInt(String s)

注意:您应该遵循java naming convention

您的代码应如下所示:

public class Age {
    public static void main(String args[]) {
        int age = 0;

        try {
            // convert age from character to integer 
            age = Integer.parseInt(args[0]) ;
            // check input age value
            // if ueser inputs age less or equal to 12
            if(age <= 12)
                System.out.println("You are very young");
            // if user enters age larger than 12 and less than 20
            if(age > 12 && age < 20)
                System.out.println("You are a teen");
            // if user enters age larger than 20
            if (age > 20)
                System.out.println("wow " + age + " is very old");
        } catch (NumberFormatException e){
            System.out.println("Error in the input enter a number");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Not enough arguments on the command line" ); 
        }
    }
}

但是当用户输入20时,此代码仍然会出现意外情况,因为在这种情况下程序没有输出任何内容。要解决此问题,您应该更改

// if user enters age larger than 20
if (age > 20)

// if user enters age at least 20
if (age >= 20)