【问题标题】:Validating the amount of command line arguments验证命令行参数的数量
【发布时间】:2014-06-05 21:40:30
【问题描述】:

我正在尝试验证只传递了三个参数。在这个程序中,我希望使用类似于 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]);
}
}

【问题讨论】:

  • 当参数少于三个时会发生什么?在我看来,它可能会生成一个ArrayIndexOutOfBoundsException

标签: java command-line-arguments args


【解决方案1】:

在检查有多少参数之前,您的代码行假定至少有 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

【讨论】:

  • 非常感谢 rgettman。我知道这很简单,但没想到这么简单。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多