验证命令行参数的数量

时间:2014-04-21 18:57:49

标签: java command-line-arguments args

我正在尝试验证传递的参数只有三个。在这个程序中,我希望使用看起来像23 23 +的命令行参数传递两个整数。但是如果他们输入少于三个参数或多于三个参数,我想要显示错误。就像现在一样,当有三个以上的参数但不少于三个时,它会给出错误消息。任何帮助都会很棒。

public class Arithmetic {

public static void main(String[] args) {

    // setting up the variable firstNumber and secondNumber
    int firstNumber = Integer.parseInt(args[0]);
    int secondNumber = Integer.parseInt(args[1]);
    String arithmetic = args[2];


    int length = args.length;


        if(length != 3){
            System.out.println("Your suppose to enter an int, int then an operation sign like +,-,X or /.");
            return;
        }

     if (arithmetic.equals("+")) {
        int addition = firstNumber + secondNumber;
        System.out.println(args[0]+ " " + args[2] + " " + args[1] + " = " + addition);  
        int total = String.valueOf(addition).length();
        System.out.println(addition + " has the length of " + total);

    } else if (arithmetic.equals("-")) {
        int minus = firstNumber - secondNumber;
        System.out.println(args[0]+ " " + args[2] + " " + args[1]+ " = " + minus);
        int total = String.valueOf(minus).length();
        System.out.println(minus + " has the length of " + total);


    } else if (arithmetic.equals("/")) {
        int division = firstNumber / secondNumber;
        System.out.println(args[0] + " " + args[2] + " " + args[1] + " = " + division);
        int total = String.valueOf(division).length();
        System.out.println(division + " has the length of " + total);


    } else if (arithmetic.equals("x")) {
        int multiply = firstNumber * secondNumber;
        System.out.println(args[0] + " " + args[2] + " " + args[1] + " = " + multiply);         
        int total = String.valueOf(multiply).length();
        System.out.println(multiply + " has the length of " + total);


    }
    //following prints out to the console what the length of each argument is.
    System.out.println(args[0] + " has the length of " + args[0].length());
    System.out.println(args[1] + " has the length of " + args[1].length());
    System.out.println("The arguments that was passed would have been " + args[0]+ " " + args[1] + " " + args[2]);
}
}

1 个答案:

答案 0 :(得分:4)

在检查有多少参数之前,您的代码行假定至少有3个参数。移动这些行:

// setting up the variable firstNumber and secondNumber
int firstNumber = Integer.parseInt(args[0]);
int secondNumber = Integer.parseInt(args[1]);
String arithmetic = args[2];

低于你的“!= 3”支票。否则,如果输入少于3个命令行参数,在检查有多少参数之前,您将在其中一行上获得ArrayIndexOutOfBoundsException