Skip to content

Instantly share code, notes, and snippets.

@davidauza-engineer
Created March 17, 2019 03:30
Show Gist options
  • Save davidauza-engineer/fbaf87b312c90372737ddd10cac204ae to your computer and use it in GitHub Desktop.
Save davidauza-engineer/fbaf87b312c90372737ddd10cac204ae to your computer and use it in GitHub Desktop.
Console program in Java which calculates the average of an array of float numbers. The user defines the size of the array and the values for each position.
import java.util.Scanner;
public class ArrayAverage {
public static void main(String[] args) {
int arraySize = 0;
float[] array;
float average = 0;
boolean validArraySize = false;
String errorForArraySize = "\nError. The size of the array must be an integer number greater than 0.";
boolean validFloatNumber = false;
Scanner sc = new Scanner(System.in);
System.out.println("\nWelcome to the program to calculate the average of an array of float numbers.");
while (!validArraySize) {
System.out.println("\nPlease insert the size of the array:");
if (sc.hasNextInt()) {
arraySize = sc.nextInt();
if (arraySize > 0) {
validArraySize = true;
} else {
// The user entered an integer number less than or equal to 0
System.out.println(errorForArraySize);
}
} else {
// The user did not enter an integer number.
System.out.println(errorForArraySize);
}
sc.nextLine();
}
array = new float[arraySize];
for (int i = 0; i < array.length; i++) {
while (!validFloatNumber) {
System.out.println("\nPlease insert a float number for position " + i + ":");
if (sc.hasNextFloat()) {
array[i] = sc.nextFloat();
validFloatNumber = true;
System.out.println("\nYou have entered " + array[i] + " for position " + i);
sc.nextLine();
} else {
System.out.println("\nError. Not a valid float number.");
sc.next();
}
}
validFloatNumber = false;
}
sc.close();
for (int i = 0; i < array.length; i++) {
average += array[i];
}
average = average / array.length;
System.out.println("\nThe average is: " + average);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment