args.length is the number of arguemnts. array is an array, then array.length is the length of the array
(you will learn array later).
public class ArgTest {
public static void main(String[] args) {
System.out.println("There are " + args.length + " arguments.");
}
}
|
Z:\>java ArgTest abc def There are 2 arguments. Z:\>java ArgTest 12 23 44 55 There are 4 arguments. Z:\>java ArgTest "Charles Li" "Amy Johnson" "Adam Smith" There are 3 arguments. Z:\>java ArgTest There are 0 arguments. |
args[i] is the i-th argument.
public class ArgTest2 {
public static void main(String[] args) {
for(int i = 0; i < args.length; i++) {
System.out.println("argument " + i + " : " + args[i]);
}
}
}
|
Z:\>java ArgTest2 abc def argument 0 : abc argument 1 : def Z:\>java ArgTest2 12 23 44 55 argument 0 : 12 argument 1 : 23 argument 2 : 44 argument 3 : 55 Z:\>java ArgTest2 "Charles Li" "Amy Johnson" "Adam Smith" argument 0 : Charles Li argument 1 : Amy Johnson argument 2 : Adam Smith |
args[i] is of type StringString to a double or an intDouble.parseDouble(args[i]) returns the double represented by args[i].Integer.parseInt(args[i]) returns the integer represented by args[i].
public class Compare {
public static void main(String[] args) {
if(args.length != 2) { // if the number of arguments is not 2
System.out.println("Please use exactly 2 arguments.");
} else {
// return the double represented by args[0]
double num1 = Double.parseDouble(args[0]);
double num2 = Double.parseDouble(args[1]);
if(num1 > num2) {
System.out.println("The first argument is bigger.");
} else if(num1 < num2) {
System.out.println("The second argument is bigger.");
} else {
System.out.println("The two arguments are equal.");
}
}
}
}
|
Z:\>java Compare 2.3 5.79 The second argument is bigger. Z:\>java Compare 3.1 -0.9 The first argument is bigger. Z:\>java Compare Please use exactly 2 arguments. Z:\>java Compare 1.2 5.9 4.21 Please use exactly 2 arguments. Z:\>java Compare 2.11 2.11 The two arguments are equal. |
java Compare 1.2 b.c ?