W rite a simple command line Java program to calculate the average from a series
ID: 3537761 • Letter: W
Question
Write a simple command line Java program to calculate the average from a series of integers the User enters at the command line interactively. In this project you are required to use the Scanner class and methods to get the Users input. Additionally a static method should be created to actually calculate the average. As the integers are entered, place them into an array. It is this array that should be passed to your average method. The array should hold a maximum of 20 integers. Again, it is acceptable for the program to crash and burn if invalid data (something other than integers) is entered.<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
Examples:
When the program first opens, the user sees the below and enters a 2:
You have entered 0 numbers, please enter a number or q to quit: 2
After the user has entered 5 numbers they enter a q to calculate the average and quit the program:
You have entered 4 numbers, please enter a number or q to quit: q
The display might be:
The average of 2, 1, 3, 4 is: 2.5
Explanation / Answer
import java.util.*;
class tset
{
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
char ch='X';
int[] a = new int[20];
int count= 0;
while(ch!='q')
{
System.out.println("You have entered " + count +" numbers, please enter a number or q to quit: ");
String input = in.next();
ch = input.charAt(0);
if(ch=='q')
break;
a[count]=Integer.parseInt(input);
count++;
}
System.out.print("The average of ");
for(int i=0; i<count; i++)
{
System.out.print("" + a[i]);
if(i!=count-1)
System.out.print(",");
}
System.out.print("is: "+ calculateAverage(a,count));
}
public static double calculateAverage(int a[],int size)
{
int sum = 0;
for(int i =0; i<size; i++)
{
sum = sum + a[i];
}
return (double)(sum)/ (double)(size);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.