Create a simple command line Java program to calculate the average of a variable
ID: 3537552 • Letter: C
Question
Create a simple command line Java program to calculate the average of a variable quantity of integers that are passed as an argument when the program is called. This uses the args array from main - you should not create or use a Scanner object. When the program is launched, have it display a welcome message. Also make sure to have the program display a help message if the user forgets to give any integers as the argument.<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
Example of calling the program with arguments:
java Average 1 2 3 4 5 6
The result of the above should be something similar to:
Welcome to the Average Program. It is very average really.
The average is: 3.5
Example of calling the program without arguments:
java Average
The result might be:
Welcome to the Average Program. It is very average really.
Usage: java Average X ( X is 1 or more integers )
Note: You do not need to deal with invalid input. For example if the user enters:
java Average kiwi 12.3 the_color_blue
...it is acceptable for the program to crash and burn.
Explanation / Answer
public class Average
{
static int sum =0;
static float average = 0;
public static void main(String[] args)
{
if(args.length == 0){
System.out.println("Welcome to the Average Program. It is very average really."+ " " +""
+ "Usage: java Average X ( X is 1 or more integers )");
}else{
for(int i=0; i< args.length;i++)
sum = sum + Integer.parseInt(args[i]);
average = sum / args.length;
System.out.println("Welcome to the Average Program. It is very average really."+ " " +""
+ "The average is:" + average);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.