Java Reference
In-Depth Information
To sort employee.txt file in ascending order:
java com.jdojo.array.SortFile employee.txt asc
To sort department.txt file in descending order:
java com.jdojo.array.SortFile department.txt desc
To sort salary.txt in ascending order:
java com.jdojo.array.SortFile salary.txt
Depending on the second element, if any, of the String array passed to the main() method of the SortFile class,
you may sort the file differently.
Note that all command-line arguments are passed to the main() method as a String . If you pass a numeric
argument, you need to convert the string argument to a number. To illustrate this numeric argument conversion, let's
develop a mini calculator class, which takes an expression as command-line argument and prints the result. The mini
calculator supports only four basic operations: add, subtract, multiply and divide; see Listing 15-10.
Listing 15-10. A Mini Command-line Calculator
// Calc.java
package com.jdojo.array;
import java.util.Arrays;
public class Calc {
public static void main(String[] args) {
// Print the list of commandline argument
System.out.println(Arrays.toString(args));
// Make sure we received three arguments and the
// the second argument has only one character to indicate operation.
if (!(args.length == 3 && args[1].length() == 1)) {
printUsage();
return; // Stop the program here
}
// Parse the two number operands. Place the parsing code inside a try-catch,
// so we will handle the error in case both operands are not numbers.
double n1 = 0.0;
double n2 = 0.0;
try {
n1 = Double.parseDouble(args[0]);
n2 = Double.parseDouble(args[2]);
}
catch (NumberFormatException e) {
System.out.println("Both operands must be a number");
printUsage();
return; // Stop the program here
}
 
Search WWH ::




Custom Search