Advertisement
Guest User

Untitled

a guest
Dec 12th, 2019
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.60 KB | None | 0 0
  1. package weightedavgdataanalyzer;
  2.  
  3. import java.io.File;
  4. import java.io.FileNotFoundException;
  5. import java.io.IOException;
  6. import java.util.Scanner;
  7. import java.util.NoSuchElementException;
  8.  
  9. public class WeightedAvgDataAnalyzer {
  10.  
  11.    public static void main(String[] args) throws IOException
  12.    {
  13.       Scanner in = new Scanner(System.in);
  14.  
  15.       boolean done = false;
  16.       while (!done){
  17.          try{
  18.             System.out.print("Please enter the file name: ");
  19.             String filename = in.next();
  20.            
  21.             double[] data = readFile(filename);
  22.  
  23.            
  24.  
  25.             double sum = 0;
  26.             for (double d : data) { sum = sum + d; }
  27.             System.out.println("The sum is " + sum);
  28.  
  29.             done = true;
  30.          }
  31.          catch (FileNotFoundException exception){
  32.             System.out.println("File not found.");
  33.          }
  34.          catch (NoSuchElementException exception){
  35.             System.out.println("File contents invalid.");
  36.          }
  37.  
  38.       }
  39.    }
  40.  
  41.    public static double[] readFile(String filename) throws IOException
  42.    {
  43.       File inFile = new File(filename);
  44.       try(Scanner in = new Scanner(inFile)) {
  45.          return readData(in);
  46.       }
  47.    }
  48.  
  49.    public static double[] readData(Scanner in) throws IOException
  50.    {    
  51.       int numberOfValues = in.nextInt();
  52.       double[] data = new double[numberOfValues];
  53.  
  54.       for (int i = 0; i < numberOfValues; i++){
  55.          data[i] = in.nextDouble();
  56.       }
  57.  
  58.       if (in.hasNext()){
  59.          throw new IOException("End of file expected");
  60.       }
  61.       return data;
  62.    }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement