发生NumberFormatException时如何打印?

时间:2015-07-30 15:39:32

标签: java command-line-arguments

当命令行参数不是整数且出现NumberFormatException时,如何打印某些内容?

我的程序需要3个命令行参数,并根据它们的内容打印某些文本。

以下是代码:

    public class CommandLine {

  public static void main(String[] args) {

      if(args.length !=3){
          System.out.println("Error. Must give 3 values");
        }
     int x = Integer.parseInt(args[0]);
     int y = Integer.parseInt(args[1]);
     int z = Integer.parseInt(args[2]);

     if((x%2)==0 && (y%2)==0 &&(z%2)==0)
     System.out.println("Even");

else
    System.out.println("odd");

  }

}

3 个答案:

答案 0 :(得分:2)

您可以捕获该异常并打印:

int x=y=z=Integer.MIN_VALUE;
try{
   x = Integer.parseInt(args[0]);
   y = Integer.parseInt(args[1]);
   z = Integer.parseInt(args[2]);
}catch (NumberFormatException e) {
   System.out.println("x:" +x + " y:" +y +" z:" +z); 
   e.printStackTrace();
}

仍为Integer.MIN_VALUE的第一个值导致您的例外(除非您的号码为Integer.MIN_VALUE

答案 1 :(得分:1)

       if(args.length !=3){
          System.out.println("Error. Must give 3 values");
        }
        else//if the above condition if true so skip these statements
        {
    try
    {
     int x = Integer.parseInt(args[0]);
     int y = Integer.parseInt(args[1]);
     int z = Integer.parseInt(args[2]);

     if((x%2)==0 && (y%2)==0 &&(z%2)==0)
     System.out.println("Even");

    else
    System.out.println("odd");
    }
    catch(NumberFormatException ne)
    {
      System.out.println("Plz! pass only integer values");//catching number format exception
    }
    }

答案 2 :(得分:1)

试试这个

     public class CommandLine {

      public static void main(String[] args) {

          if(args.length !=3){
              System.out.println("Error. Must give 3 values");
            }
         try{
         int x = Integer.parseInt(args[0]);
         int y = Integer.parseInt(args[1]);
         int z = Integer.parseInt(args[2]);

         if((x%2)==0 && (y%2)==0 &&(z%2)==0)
         System.out.println("Even");

    else
        System.out.println("odd");


    }catch(Exception e){
     System.out.println("Exception Caught !");
    }
    }
}