In: Computer Science
JAVA
Lab 0.2 — Calculating Averages (Averages)
The file numbers.text consists of sequences of numbers, each sequence preceded by a header value and then followed by that many integers/ (For example the first line in the example below contains a header value of 3 followed by the three values 1, 2, and 3. Read in the sequences and print their averages. When all sequences have been read in, print out the number of sequences processed.
The header and subsequent values are placed on the same line for readability, but could just have easily been spread across two or more line, i.e., you don't have to process them using nextLine; simply read them in using nextInt.)
The name of your class should be Averages.
Sample Test Run
For example if the file numbers.text contains:
3 1 2 3 5 12 14 6 4 0 10 1 2 3 4 5 6 7 8 9 10 1 17 2 90 80
the program should produce the following output:
The average of the 3 integers 1 2 3 is 2.0 The average of the 5 integers 12 14 6 4 0 is 7.2 The average of the 10 integers 1 2 3 4 5 6 7 8 9 10 is 5.5 The average of the 1 integers 17 is 17.0 The average of the 2 integers 90 80 is 85.0 5 sets of numbers processed
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Averages { public static void main(String[] args) { File file = new File("numbers.text"); try { Scanner fin = new Scanner(file); int numSets = 0; while (fin.hasNextInt()) { int n = fin.nextInt(), num, count = 0; double total = 0; String s = ""; for (int i = 0; i < n; i++) { num = fin.nextInt(); total += num; ++count; s += num + " "; } System.out.println("The average of the " + count + " integers " + s + "is " + (total/count)); ++numSets; } System.out.println(numSets + " sets of numbers processed"); fin.close(); } catch (FileNotFoundException e) { System.out.println(file.getAbsolutePath() + " is not found!"); } } }