-
Notifications
You must be signed in to change notification settings - Fork 104
/
Copy pathExercise12_23.java
47 lines (40 loc) · 1.63 KB
/
Exercise12_23.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
package ch_12;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import java.util.regex.Pattern;
/**
* **12.23 (Process scores in a text file on the Web) Suppose that the text file on the
* Web http://cs.armstrong.edu/liang/data/Scores.txt contains an unspecified number
* of scores. Write a program that reads the scores from the file and displays their
* total and average. Scores are separated by blanks.
*/
public class Exercise12_23 {
public static void main(String[] args) {
double total = 0, average = 0;
int count = 0;
try {
// URL url = new URL("http://cs.armstrong.edu/liang/data/Scores.txt"); No longer online
URL url = new URL("https://git.savannah.gnu.org/cgit/datamash.git/plain/examples/scores.txt");
try (Scanner in = new Scanner(url.openStream())) {
while (in.hasNext()) {
double score;
String nxtStr = in.next();
if (Character.isDigit(nxtStr.charAt(0))) {
score = Double.parseDouble(nxtStr);
count++;
total += score;
}
}
System.out.println("The total is " + total);
average = total / count;
System.out.printf("The average score was %.2f%n", average);
} catch (IOException ioe) {
ioe.printStackTrace();
}
} catch (MalformedURLException malformedURLException) {
malformedURLException.printStackTrace();
}
}
}