Skip to content

Instantly share code, notes, and snippets.

@ParadauxIO
Created November 2, 2020 16:29
Show Gist options
  • Save ParadauxIO/85e980efcc240be0772a2cad754c19e5 to your computer and use it in GitHub Desktop.
Save ParadauxIO/85e980efcc240be0772a2cad754c19e5 to your computer and use it in GitHub Desktop.
Calculate the average of the provided integers
import java.util.InputMismatchException;
import java.util.Scanner;
public class TotalAverageCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int populationSum = 0;
int populationSize;
System.out.print("How many integers do you want to enter? ");
try {
populationSize = scanner.nextInt();
} catch (InputMismatchException exception) {
System.out.println("You entered an invalid integer.");
scanner.close();
return;
}
if (populationSize < 2 || populationSize > 10) {
System.out.println("Error: This program is constrained to only compute the total & average of between 2 & 10 integers.");
return;
}
// Before you say this is wrong because I used a single letter variable, according to oracle's Java Specification, single letter variable names
// Following the pattern i, j, k, m, etc are perfectly fine for the purposes of iteration.
// See: https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html "Variables"
// Get the sum of the values in the list
try {
for (int i = 0; i <= populationSize-1; i++) {
System.out.printf("Enter integer %d: ", i+1);
populationSum += scanner.nextInt();
}
} catch (InputMismatchException exception) {
System.out.println("You entered an invalid integer.");
scanner.close();
return;
}
// web-CAT requires this to be done, even though the heap will be destroyed momentarily.
scanner.close();
// Calculate the mean and ensure its division in a floating-point context
double mean = (double) populationSum / populationSize;
System.out.printf("The sum of your integers is %d and the average is %.2f", populationSum, mean);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment