The file numbers.text conisits of sequences of numbers, each sequence preceded by a header value nd then 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.(you must use file I/O in Java)
The name of your class should be Averages.
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) { Scanner in = new Scanner(System.in); 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!"); } in.close(); } }
Get Answers For Free
Most questions answered within 1 hours.