Activity1: Command line programming.
Program File : Sum.java
Procedures : 1. Type the program file.
: 2. Save/Compile the program.
: 3. Using the Command Prompt (C:\>), execute the following:
Path = C:\jdk\bin (or look for the equivalent directory)
Javac Sum.java (compiling the program)
Java Sum 2 3 (running the program with test data)
: 4. The result should look like this:
The sum is: 5.0
: 5. If the command
java Sum 5
or
java Sum 1 2 3
is executed, a message “Invalid number of inputs!” will be displayed.
public class Sum
{
static double n1, n2;
public static void main( String args[] )
{
int numArgs = args.length;
if( numArgs >2 || numArgs < 2 )
System.out.println( “Invalid number of inputs.” );
else
{
n1 = Double.parseDouble( args[0] );
n2 = Double.parseDouble( args[1] );
System.out.println( “The sum is: ” + (n1+n2));
}
}
}
Note: In the command Java Sum 2 3, the first number 2 is args[0] while 3 is args[1].
The method length will count the number of arguments based from the user inputs.