Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.util.Scanner;
- import java.util.NoSuchElementException;
- import java.util.*;
- 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();
- System.out.println();
- ArrayList<Double> data = readFile(filename);
- System.out.println("Weighted average: " + calcWeightedAverage(data));
- done = true;
- }
- catch (FileNotFoundException exception){
- System.out.println("File not found.");
- return;
- }
- catch (NoSuchElementException exception){
- System.out.println("File contents invalid.");
- }
- catch (IOException exception){
- exception.printStackTrace();
- }
- }
- }
- public static ArrayList<Double> readFile(String filename) throws IOException{
- File inFile = new File(filename);
- try(Scanner in = new Scanner(inFile)) {
- return readData(in);
- }
- }
- public static ArrayList<Double> readData(Scanner in) throws IOException{
- String[] nameOfStringArray;
- ArrayList<Double> data = new ArrayList<>();
- // grab all the data from the file
- try {
- if (in.hasNextLine()) {
- nameOfStringArray = in.nextLine().split(" ");
- for (String stringElement : nameOfStringArray) {
- data.add(Double.parseDouble(stringElement));
- }
- }
- }
- catch (Exception e) {}
- return data;
- }
- private static double getWeight(ArrayList<Double> data) {
- return data.get(0);
- }
- private static int getDrop(ArrayList<Double> data) {
- return data.get(1).intValue();
- }
- public static double calcWeightedAverage(ArrayList<Double> data) {
- double weight = getWeight(data);
- int drops = getDrop(data);
- for (int i = 0; i < drops; i++){
- int minIntIndex = 2;
- for (int x = 3; x < data.size(); x++){
- System.out.println(data.get(x));
- System.out.println(data.get(minIntIndex));
- if (data.get(x) < data.get(minIntIndex)) {
- minIntIndex = x;
- }
- //data.remove(minIntIndex);
- }
- System.out.println("Dropping value: " + data.get(minIntIndex));
- data.remove(minIntIndex);
- System.out.println("List is: " + data);
- }
- data.remove(0);
- data.remove(0);
- ArrayList<Double> newArray = new ArrayList<>(data);
- for(int i = 0; i < newArray.size(); i++) {
- newArray.set(i, newArray.get(i) * weight);
- }
- double sum = 0.0;
- for(int i = 0; i < newArray.size(); i++){
- sum += newArray.get(i);
- }
- double average = sum / newArray.size();
- return average;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement