-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArraysH.java
73 lines (50 loc) · 2.01 KB
/
ArraysH.java
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class ArraysH {
public static void main(String[] args) throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the file name: ");
String fileName = keyboard.nextLine();
File file = new File(fileName);
while (!file.exists()) {
System.out.printf("File '%s' does not exist.\n", fileName);
System.out.println("Please enter the file name again: ");
fileName = keyboard.nextLine();
file = new File(fileName);
}
if (file.exists()) {
ArrayList<ArrayList<Double>> spreadsheet = load(file);
System.out.printf("Total: %,.3f\n", getTotal(spreadsheet));
System.out.printf("Average: %,.3f\n", getAverage(spreadsheet));
}
}
private static double getTotal(ArrayList<ArrayList<Double>> table) {
double sum = 0.0 ;
for(ArrayList<Double> row : table) {
for(double number : row) {
sum += number;
}
}
return sum;
}
private static double getAverage(ArrayList<ArrayList<Double>> table) {
return getTotal(table)/ table.size() / table.get(0).size();
}
private static ArrayList<ArrayList<Double>> load(File file) throws FileNotFoundException {
Scanner inputFile = new Scanner(file);
ArrayList<ArrayList<Double>> result = new ArrayList<>();
while(inputFile.hasNext()) {
String line = inputFile.nextLine();
result.add(new ArrayList<Double>());
Scanner numbers = new Scanner(line);
while(numbers.hasNext()) {
result.get(result.size() -1).add(numbers.nextDouble());
}
numbers.close();
}
inputFile.close();
return (result);
}
}