Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

E XERCISE 1: P ROCESSING C OMMAND L INE A RGUMENTS Write a program called Averag

ID: 654698 • Letter: E

Question

E XERCISE 1: P ROCESSING C OMMAND L INE A RGUMENTS Write a program called Average that accepts zero or more integers as command line arguments and calculates the average of all the numbers passed into the program. Here is an example running the program from the command line:

C: > java Average 10 5 10 5

With command line arguments 10, 5, 10, 5, the program should output the Average like this:

AVERAGE = 7.5

The program should use exception handling to handle situations where a command line argument has been give n that is not a valid integer. Here is an example: C: > java Average 10 five 10 5 Error:

The argument

Explanation / Answer

import java.util.Scanner;


public class MyAverage
{

public static void main(String args[])
    {
         int num = 0, count = 0, total = 0;
         Scanner in = new Scanner(System.in);
       
         while (num != -99)
            {
              System.out.print("Enter a whole number, and -99 to quit: ");
              num = in.nextInt(); // accept input
              if (num != -99)
              {
                count++; // increment counter
                total += num; //accumulate the sum
              }
            }
         float average = (float) total/count;
         System.out.println("You keyed in " + new Integer(count) + " numbers ");
         System.out.println("The average is: " + new Float(average));
    }
}