PIC20A Lecture 5

How to find the number of arguments?

public class ArgTest {
   public static void main(String[] args) {
       System.out.println("There are " + args.length + " arguments.");
   }
}   
Sample output
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.

How to access arguments?

public class ArgTest2 {
    public static void main(String[] args) {
        for(int i = 0; i < args.length; i++) {
            System.out.println("argument " + i + " : " + args[i]);
        }
    }
}
Sample output
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

How to change String to other primitive types?

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.");
            }
        }
    }
}

Sample Output
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.

Question What is the output of java Compare 1.2 b.c ?