// read in a list of batting averages (doubles) as command line arguments
public class battingAverage {
public static void main (String[] args) {
int argc = args.length; // this tells us how many command line arguments there are
double[] ba = new double [args.length]; // allocate space for each command line argument
for (int i = 0; i< argc; i++) {
ba[i] = Double.parseDouble(args[i]); // does the coversion from String to double
System.out.printf("found batting average: %d %1.3f \n", i, ba[i]); // just to trace the program
// notice this uses printf and I want the batting averages to always
// show 3 decimal places
}
for (int i = 0; i< ba.length; i++) {
System.out.printf("Batting average: [%d] = %1.3f \n", i, ba[i]);
// notice this uses printf and I want the batting averages to always
// show 3 decimal places
}
// sort the array - from low to high
// First find the lowest value, put it in ba[0],
// fint the next lowest value, put it in ba[1]..and so on
// Efficiency is not a consideration here
for (int i = 0; i < (ba.length - 1); i++) {
for (int j = i+1; j < ba.length; j++) {
if (ba[i] > ba[j]) { // switch the two
double temp = ba[i]; // save it
ba[i] = ba[j]; // move lower number toward start
ba[j] = temp; // move higher numbers toward end
}
} // j loop
} // i loop
System.out.println("\nThe sorted batting averages:\n");
for (int i = 0; i< ba.length; i++) {
System.out.printf("Batting average: [%d] = %1.3f \n", i, ba[i]);
// notice this uses printf and I want the batting averages to always
// show 3 decimal places
}
}
}
|