In this post, we’ll see various ways of calculating average of n numbers in Java.
1) Average of 3 input numbers
2) Average of n numbers input by user
3) Average of the numbers in an array
Average of 3 input numbers:
package com.techstackjournal.average;
import java.util.InputMismatchException;
import java.util.Scanner;
public class AverageOfNumbersExample1 {
public static void main(String[] args) {
int counter = 1, num, sum = 0, avg;
Scanner scanner = new Scanner(System.in);
while (counter <= 3) {
System.out.println("Enter num " + counter + " : ");
try {
num = scanner.nextInt();
} catch (InputMismatchException ex) {
scanner.nextLine();
System.out.println("Enter a valid number");
continue;
}
scanner.nextLine();
sum += num;
counter++;
}
scanner.close();
avg = sum / (counter - 1);
System.out.println("Average of 3 numbers is: " + avg);
}
}
We are calling nextLine to read the newline character entered after the number. If we do not do this, next time when nextInt is called it may not found the number.
Enter num 1 :
2
Enter num 2 :
r
Enter a valid number
Enter num 2 :
4
Enter num 3 :
6
Average of 3 numbers is: 4
Average of n numbers input by user:
package com.techstackjournal.average;
import java.util.Scanner;
public class AverageOfNumbersExample2 {
public static void main(String[] args) {
int counter = 1, num, sum = 0, avg;
String tempStr;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Enter num " + counter + " : ");
tempStr = scanner.nextLine();
if (tempStr.equalsIgnoreCase("Q")) {
break;
}
try {
num = Integer.parseInt(tempStr);
} catch (NumberFormatException ex) {
System.out.println("Enter a valid number");
continue;
}
sum += num;
counter++;
}
scanner.close();
avg = sum / (counter - 1);
System.out.println("Average of " + (counter - 1) + " numbers is: " + avg);
}
}
Enter num 1 :
5
Enter num 2 :
f
Enter a valid number
Enter num 2 :
5
Enter num 3 :
5
Enter num 4 :
q
Average of 3 numbers is: 5
Average of the numbers in an array:
package com.techstackjournal.average;
public class AverageOfNumbersExample3 {
public static void main(String[] args) {
int[] nums = { 2, 4, 6, 8, 10 };
int sum = 0, avg;
for (int n : nums) {
sum += n;
}
avg = sum / nums.length;
System.out.println("Average of " + nums.length + " numbers is: " + avg);
}
}
Average of 5 numbers is: 6