Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package weightedavgdataanalyzer;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.util.Scanner;
- import java.util.NoSuchElementException;
- public class WeightedAvgDataAnalyzer {
- public static void main(String[] args) throws IOException
- {
- Scanner in = new Scanner(System.in);
- boolean done = false;
- while (!done){
- try{
- System.out.print("Please enter the file name: ");
- String filename = in.next();
- double[] data = readFile(filename);
- double sum = 0;
- for (double d : data) { sum = sum + d; }
- System.out.println("The sum is " + sum);
- done = true;
- }
- catch (FileNotFoundException exception){
- System.out.println("File not found.");
- }
- catch (NoSuchElementException exception){
- System.out.println("File contents invalid.");
- }
- }
- }
- public static double[] readFile(String filename) throws IOException
- {
- File inFile = new File(filename);
- try(Scanner in = new Scanner(inFile)) {
- return readData(in);
- }
- }
- public static double[] readData(Scanner in) throws IOException
- {
- int numberOfValues = in.nextInt();
- double[] data = new double[numberOfValues];
- for (int i = 0; i < numberOfValues; i++){
- data[i] = in.nextDouble();
- }
- if (in.hasNext()){
- throw new IOException("End of file expected");
- }
- return data;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement