Task #7: Using Arrays and Methods
In this task, you are being asked to write methods that manipulate arrays in Java.
Write a method called fillArray() which will take an integer array as input and the fills the array
with the user entered numbers.
You may use the following header for this method:
static void fillArray(int[] array)
Write another method called printSumAverage() which takes an integer array as input and prints
the sum and average of the array elements.
You may use the following header for this method:
static void printSumAverage(int[] array)
Take a number from the user as the size of the array, call the method fillArray(), then call the
method printSumAverage().
NOTE: Perform input validation so that the size must be greater than 0.
1. Create a program called ArraySumAverageLab1.java.
2. Create appropriate variables and assign values using a Scanner object.
3. Correctly display appropriate messages.
import java.util.Scanner;
public class ArraySumAverageLab1 {
static Scanner keyBoard = new Scanner(System.in);
/**
* The start point of the program
*
* @param args
*
*/
public static void main(String[] args) {
System.out.print("Enter a size of array : ");
int size = keyBoard.nextInt();
if (size <= 0) {
System.out.println("The size must be greater than 0.");
} else {
int[] array = new int[size];
fillArray(array);
printSumAverage(array);
}
keyBoard.close();
}
static void fillArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print("Enter the number " + (i + 1) + ": ");
array[i] = keyBoard.nextInt();
}
}
static void printSumAverage(int[] array) {
int sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i];
}
double average = (double) sum / (double) array.length;
System.out.printf("The sum of the array element: %d\n", sum);
System.out.printf("The average of the array element: %.2f\n", average);
}
}
Comments
Leave a comment