public class Main
{
public static void main(String[] args) {
//this program requires two arguments on the command line
if (args.length == 2) {
//convert strings to numbers
float a = (Float.valueOf(args[0]) ).floatValue();
float b = (Float.valueOf(args[1]) ).floatValue();
//do some arithmetic
System.out.println("a + b = " + (a + b) );
System.out.println("a - b = " + (a - b) );
System.out.println("a * b = " + (a * b) );
System.out.println("a / b = " + (a / b) );
System.out.println("a % b = " + (a % b) );
} else {
System.out.println("This program requires two command-line arguments.");
}
}
}
For the above program, type this at the command line:
javac Main.java
then this:
java Main 5 6
"5" is args[0]. "6" is args[1]. They are parameters passed to the main function from the command line. The program requires that you pass it two parameters because that's what it needs to do its job. In line 5, it checks to make sure you've passed it two parameters, and if you haven't, you get an error message. Thus the following will all result in an error message:
java Main
java Main 5
java Main 5 6 7
These lines pass main 0, 1, and 3 arguments. It needs 2. Replace the numbers 5 and 6 with any numbers you like, but you must supply the program two numbers for the program to work.
VernonDozier
Posting Expert
5,675 posts since Jan 2008
Reputation Points: 2,633
Solved Threads: 738
Skill Endorsements: 18
Start your own thread if you have problems. Don't hijack someone else's very dead thread.
NormR1
Posting Sage
7,742 posts since Jun 2010
Reputation Points: 1,158
Solved Threads: 793
Skill Endorsements: 16