Java 程序从命令行获取输入,并进行异常处理

Java program taking input from the command line, with exception handling

再次需要帮助。该程序是将输入作为年龄并根据输入抛出异常。它会在程序运行时从命令行获取用户的年龄,如果用户没有在命令行上输入数字或输入错误,程序应该处理问题。

我的代码是:

 public class Age2 {

    public static void main(String args[]){

        try{
            int age = Integer.parseInt(args[0]);  //taking in an integer input throws NumberFormat Exception if not an integer

            if(age<= 12)
               System.out.println("You are very young");

            else if(age > 12 && age <= 20)
               System.out.println("You are a teenager");

            else
                System.out.println("WOW "+age+" is old");
        }

        catch(NumberFormatException e){   //is input is not an integer, occurs while parsing the command line input argument
            System.out.println("Your input is not a number");

        }catch(ArrayIndexOutOfBoundsException e){ //as takes in input from command line which is stored to a Args array in main, if this array is null implies no input given
            System.out.println("Please enter a number on the command line");
        }

    }   
}//end class

我的输出:

但是如果用户犯了任何错误,程序也应该显示异常:

“22 22”或“3 kjhk”

见下图:

你能帮我修改一下吗? 谢谢大家

你必须做

catch(exception e){
  e.printstacktrace // or something like that to get your exception
  System.out.println("thats not a number")}

你现在的方式就是告诉程序在出现异常时输出你的字符串。

程序仍会正常运行,因为您参考 args[0] 并且从命令行给出的参数由空格分隔,因此即使您添加其他参数也总是 22。

您可以简单地验证年龄是唯一给定的参数。

if(args.length > 1)
   throw new Exception();

如果传递 22 22kjj,args 将有两个元素:2222kjj

您可以添加条件:if(args.length != 1) System.out.println("only one number");

使用

调用程序时

java Age2 22 22kjj

您将获得“22”和“22kjj”作为程序参数数组的独立成员:

  1. args[0] 包含“22”
  2. args[1] 包含“22kjj”

因为您只检查了 args[0],所以您不会遇到格式错误的 args[1] 的任何问题。也许你还想检查参数数组的长度:

if (args.length != 1) {
    System.out.println("Please enter exactly one number!");
}

调用你的程序
java Age2 "22 22kjj"

或与

java Age2 "22kjj"

会给你想要的输出。

之所以有效,是因为 args[0] 传递了第一个参数。您需要做的是检查 args[1].

例如

public class Age2 {

public static void main(String args[]){
if(args.length == 1)
{
    try{
        int age = Integer.parseInt(args[0]);  //taking in an integer input throws NumberFormat Exception if not an integer

        if(age<= 12)
           System.out.println("You are very young");

        else if(age > 12 && age <= 20)
           System.out.println("You are a teenager");

        else
            System.out.println("WOW "+age+" is old");
    }

    catch(NumberFormatException e){   //is input is not an integer, occurs while parsing the command line input argument
        System.out.println("Your input is not a number");

    }catch(ArrayIndexOutOfBoundsException e){ //as takes in input from command line which is stored to a Args array in main, if this array is null implies no input given
        System.out.println("Please enter a number on the command line");
    }


 }else{
   System.out.println("Pls give a single Number");
  }
}//end class