The file numbers.text consists of sequences of numbers, each sequence preceded by a header value and followed by that many integers. Read in the sequences and print their averages. When all sequences have been read in, print out the number of sequences processed.
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 3 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
My Output
The·average·of·the·3·integers·6·is·2.0↵
The·average·of·the·5·integers·36·is·7.2↵
The·average·of·the·10·integers·55·is·5.5↵
The·average·of·the·1·integers·17·is·17.0↵
The·average·of·the·2·integers·170·is·85.0↵
5·sets·of·numbers·processed↵
Correct 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·1 0·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↵
My code:
import java.util.Scanner; import java.io.File; class Averages { public static void main(String args[]) throws Exception { Scanner filename = new Scanner(new File("numbers.text")); int numSequences = 0; while (filename.hasNextInt()) { int numLength = filename.nextInt(); int numSum = 0; for (int i = 0; i < numLength; i++) { numSum += filename.nextInt(); } double numAverage = (double) numSum / numLength; System.out.println("The average of the " + numLength + " integers " + numSum + " is " + numAverage); numSequences++; } System.out.println(numSequences + " sets of numbers processed"); } }