【发布时间】: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