Java Reference
In-Depth Information
The program is shown in Listing 7.9.
L ISTING 7.9
Calculator.java
1 public class Calculator {
2 /** Main method */
3 public static void main(String[] args) {
4 // Check number of strings passed
5 if (args.length != 3 ) {
6 System.out.println(
7 "Usage: java Calculator operand1 operator operand2" );
8 System.exit( 0 );
9 }
10
11
check argument
// The result of the operation
12
int result = 0 ;
13
14 // Determine the operator
15 switch (args[ 1 ].charAt( 0 )) {
16 case '+' : result = Integer.parseInt(args[ 0 ]) +
17 Integer.parseInt(args[ 2 ]);
18 break ;
19 case '-' : result = Integer.parseInt(args[ 0 ]) -
20 Integer.parseInt(args[ 2 ]);
21 break ;
22 case '.' : result = Integer.parseInt(args[ 0 ]) *
23 Integer.parseInt(args[ 2 ]);
24 break ;
25 case '/' : result = Integer.parseInt(args[ 0 ]) /
26 Integer.parseInt(args[ 2 ]);
27 }
28
29 // Display result
30 System.out.println(args[ 0 ] + ' ' + args[ 1 ] + ' ' + args[ 2 ]
31 + " = " + result);
32 }
33 }
check operator
Integer.parseInt(args[0]) (line 16) converts a digital string into an integer. The string
must consist of digits. If not, the program will terminate abnormally.
We used the . symbol for multiplication, not the common * symbol. The reason for this is
that the * symbol refers to all the files in the current directory when it is used on a command
line. The following program displays all the files in the current directory when issuing the
command java Test * :
public class Test {
public static void main(String[] args) {
for ( int i = 0 ; i < args.length; i++)
System.out.println(args[i]);
}
}
To circumvent this problem, we will have to use a different symbol for the multiplication operator.
7.29
This topic declares the main method as
public static void main(String[] args)
Can it be replaced by one of the following lines?
public static void main(String args[])
public static void main(String[] x)
Check
Point
 
Search WWH ::




Custom Search