-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAverageCalculator.java
More file actions
39 lines (29 loc) · 1.11 KB
/
AverageCalculator.java
File metadata and controls
39 lines (29 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.util.ArrayList;
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a list of numbers separated by spaces:");
String userInput = scanner.nextLine();
AverageCalculator calculator = new AverageCalculator();
double average = calculator.calculateAverage(userInput);
System.out.println("The average of the inputted numbers is: " + average);
}
public double calculateAverage(String input) {
String[] strArr = input.split(" ");
ArrayList<Integer> numList = new ArrayList<>();
for(String str : strArr) {
try {
numList.add(Integer.parseInt(str));
} catch (NumberFormatException e) {
System.out.println(str + " is not a valid number");
return 0;
}
}
int total = 0;
for(int num : numList) {
total += num;
}
return numList.isEmpty() ? 0 : (double) total / numList.size();
}
}