Question

In: Computer Science

Hello, I need an expert answer for one of my JAVA homework assignments. I will be...

Hello, I need an expert answer for one of my JAVA homework assignments. I will be providing the instructions for this homework below:

For this lab, you will write the following files:

  • AbstractDataCalc
  • AverageDataCalc
  • MaximumDataCalc
  • MinimumDataCalc

As you can expect, AbstractDataCalc is an abstract class, that AverageDataCalc, MaximumDataCalc and MinimumDataCalc all inherit.

We will provide the following files to you:

  • CSVReader
    A simple CSV reader for Excel files
  • DataSet
    This file uses CSVReader to read the data into a List> type structure. This of this as a Matrix using ArrayLists. The important methods for you are rowCount() and getRow(int i)
  • Main
    This contains a public static void String[] args. You are very free to completely change this main (and you should!). We don't test your main, but instead your methods directly.

Sample Input / Output

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Given the following CSV file

1,2,3,4,5,6,7
10,20,30,40,50,60
10.1,12.2,13.3,11.1,14.4,15.5

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

The output of the provided main is:

 Dataset Results (Method: AVERAGE)
 Row 1: 4.0
 Row 2: 35.0
 Row 3: 12.8

 Dataset Results (Method: MIN)
 Row 1: 1.0
 Row 2: 10.0
 Row 3: 10.1

 Dataset Results (Method: MAX)
 Row 1: 7.0
 Row 2: 60.0
 Row 3: 15.5

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Specifications

You will need to implement the following methods at a minimum. You are free to add additional methods.

AbstractDataCalc

  • public AbstractDataCalc(DataSet set) - Your constructor that sets your dataset to an instance variable, and runCalculations() based on the dataset if the passed in set is not null. (hint: call setAndRun)
  • public void setAndRun(DataSet set) - sets the DataSet to an instance variable, and if the passed in value is not null, runCalculations on that data
  • private void runCalculations() - as this is private, technically it is optional, but you are going to want it (as compared to putting it all in setAndRun). This builds an array (or list) of doubles, with an item for each row in the dataset. The item is the result returned from calcLine.
  • public String toString() - Override toString, so it generates the format seen above. Method is the type returned from get type, row counting is the more human readable - starting at 1, instead of 0.
  • public abstract String getType() - see below
  • public abstract double calcLine(List line) - see below

AverageDataCalc

Extends AbstractDataCalc. Will implement the required constructor and abstract methods only.

  • public abstract String getType() - The type returned is "AVERAGE"
  • public abstract double calcLine(List line) - runs through all items in the line and returns the average value (sum / count).

MaximumDataCalc

Extends AbstractDataCalc. Will implement the required constructor and abstract methods only.

  • public abstract String getType() - The type returned is "MAX"
  • public abstract double calcLine(List line) - runs through all items, returning the largest item in the list.

MinimumDataCalc

Extends AbstractDataCalc. Will implement the required constructor and abstract methods only.

  • public abstract String getType() - The type returned is "MIN"
  • public abstract double calcLine(List line) - runs through all items, returning the smallest item in the list.

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

CSVReader.java


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;


public class CSVReader {
    private static final char DELIMINATOR = ',';
    private Scanner fileScanner;

  
    public CSVReader(String file) {
        this(file, true);
    }

  
    public CSVReader(String file, boolean skipHeader) {
        try {
            fileScanner = new Scanner(new File(file));
            if(skipHeader) this.getNext();
        }catch (IOException io) {
            System.err.println(io.getMessage());
            System.exit(1);
        }
    }

  
    public List<String> getNext() {
        if(hasNext()){
            String toSplit = fileScanner.nextLine();
            List<String> result = new ArrayList<>();
            int start = 0;
            boolean inQuotes = false;
            for (int current = 0; current < toSplit.length(); current++) {
                if (toSplit.charAt(current) == '\"') { // the char uses the '', but the \" is a simple "
                    inQuotes = !inQuotes; // toggle state
                }
                boolean atLastChar = (current == toSplit.length() - 1);
                if (atLastChar) {
                    result.add(toSplit.substring(start).replace("\"", "")); // remove the quotes from the quoted item
                } else {
                    if (toSplit.charAt(current) == DELIMINATOR && !inQuotes) {
                        result.add(toSplit.substring(start, current).replace("\"", ""));
                        start = current + 1;
                    }
                }
            }
            return result;
        }
        return null;
    }

  
    public boolean hasNext() {
        return (fileScanner != null) && fileScanner.hasNext();
    }

}

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

DataSet.java

import java.util.ArrayList;
import java.util.List;

public class DataSet {
    private final List<List<Double>> data = new ArrayList<>();


    public DataSet(String fileName) {
        this(new CSVReader(fileName, false));
    }

  
    public DataSet(CSVReader csvReader) {
        loadData(csvReader);
    }

  
    public int rowCount() {
        return data.size();
    }

  
    public List<Double> getRow(int i) {
        return data.get(i);
    }

  
    private void loadData(CSVReader file) {
        while(file.hasNext()) {
            List<Double> dbl = convertToDouble(file.getNext());
            if(dbl.size()> 0) {
                data.add(dbl);
            }
        }
    }

  
    private List<Double> convertToDouble(List<String> next) {
        List<Double> dblList = new ArrayList<>(next.size());
        for(String item : next) {
            try {
                dblList.add(Double.parseDouble(item));
            }catch (NumberFormatException ex) {
                System.err.println("Number format!");
            }
        }
        return dblList;
    }


  
    public String toString() {
        return data.toString();
    }
}

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Main.java

public class Main {
  
    public static void main(String[] args) {
        String testFile = "sample.csv";
        DataSet set = new DataSet(testFile);
        AverageDataCalc averages = new AverageDataCalc(set);
        System.out.println(averages);
        MinimumDataCalc minimum = new MinimumDataCalc(set);
        System.out.println(minimum);
        MaximumDataCalc max = new MaximumDataCalc(set);
        System.out.println(max);
    }
  
}

Solutions

Expert Solution

import java.util.ArrayList;
import java.util.List;

public abstract class AbstractDataCalc {
   private DataSet set; // the dataset
   private List<Double> resultsList; // the list built by runCalculations()
  
   // calls setAndRun to set dataset to an instance variable
   public AbstractDataCalc(DataSet set) {
       setAndRun(set);
   }
  
   // sets the dataSet to an instance variable, and if the passed in value is not null, runCalculations on that data
   public void setAndRun(DataSet set) {
       this.set = set;
       if(set != null)
           runCalculations();
   }
  
   // builds a list of doubles, with an item for each row in the dataset. The item is the result returned from calcLine
   private void runCalculations() {
       resultsList = new ArrayList<Double>();
       for(int i=0; i<set.rowCount(); i++)
           resultsList.add(calcLine(set.getRow(i)));
   }
  
   // generates results in a tabular form (the given format)
   @Override
   public String toString() {
       String result = "\nDataset Results (Method: " + getType() + ")";
       for(int i=0; i<resultsList.size(); i++)
           result += "\nRow " + (i+1) + ": " + String.format("%.1f",resultsList.get(i));
       return result;
   }
  
   // methods to be implemented by the subclasses
   public abstract String getType();
   public abstract double calcLine(List<Double> line) ;
}

__________________________________

import java.util.List;

public class AverageDataCalc extends AbstractDataCalc{
  
   public AverageDataCalc(DataSet set) {
       super(set); // AbstractDataCalc constructor
   }
  
   // - The type returned is "AVERAGE"
   @Override
   public String getType() {
       return "AVERAGE";
   }
  
   // - runs through all items in the line and returns the average value (sum / count).
   @Override
   public double calcLine(List<Double> line) {
       int count = line.size();
       double sum = 0;
       for(double item : line)
           sum += item;       // accumulate the sum
       return sum / count; // compute and return the average
   }

}


__________________________________

import java.util.List;

public class MaximumDataCalc extends AbstractDataCalc{
  
   public MaximumDataCalc(DataSet set) {
       super(set); // AbstractDataCalc constructor
   }
  
   // - The type returned is "MAX"
   @Override
   public String getType() {
       return "MAX";
   }
  
   // - runs through all items, returning the largest item in the list.
   @Override
   public double calcLine(List<Double> line) {
       double max = line.get(0);
       for(double item: line)
           if(item > max)
               max = item;
       return max;
   }


}


_____________________________________

import java.util.List;

public class MinimumDataCalc extends AbstractDataCalc{
   public MinimumDataCalc(DataSet set) {
       super(set); // AbstractDataCalc constructor
   }
  
   // - The type returned is "MIN"
   @Override
   public String getType() {
       return "MIN";
   }
  
   // - runs through all items, returning the smallest item in the list.
   @Override
   public double calcLine(List<Double> line) {
       double min = line.get(0);
       for(double item: line)
           if(item < min)
               min = item;
       return min;
   }

}


_________________________________________

public class Main {
  
public static void main(String[] args) {
String testFile = "sample.csv";
DataSet set = new DataSet(testFile);
AverageDataCalc averages = new AverageDataCalc(set);
System.out.println(averages);
MinimumDataCalc minimum = new MinimumDataCalc(set);
System.out.println(minimum);
MaximumDataCalc max = new MaximumDataCalc(set);
System.out.println(max);
}
  
}

_________________________________


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;


public class CSVReader {
private static final char DELIMINATOR = ',';
private Scanner fileScanner;

  
public CSVReader(String file) {
this(file, true);
}

  
public CSVReader(String file, boolean skipHeader) {
try {
fileScanner = new Scanner(new File(file));
if(skipHeader) this.getNext();
}catch (IOException io) {
System.err.println(io.getMessage());
System.exit(1);
}
}

  
public List<String> getNext() {
if(hasNext()){
String toSplit = fileScanner.nextLine();
List<String> result = new ArrayList<>();
int start = 0;
boolean inQuotes = false;
for (int current = 0; current < toSplit.length(); current++) {
if (toSplit.charAt(current) == '\"') { // the char uses the '', but the \" is a simple "
inQuotes = !inQuotes; // toggle state
}
boolean atLastChar = (current == toSplit.length() - 1);
if (atLastChar) {
result.add(toSplit.substring(start).replace("\"", "")); // remove the quotes from the quoted item
} else {
if (toSplit.charAt(current) == DELIMINATOR && !inQuotes) {
result.add(toSplit.substring(start, current).replace("\"", ""));
start = current + 1;
}
}
}
return result;
}
return null;
}

  
public boolean hasNext() {
return (fileScanner != null) && fileScanner.hasNext();
}

}

_____________________________________

import java.util.ArrayList;
import java.util.List;
public class DataSet {
private final List<List<Double>> data = new ArrayList<>();
public DataSet(String fileName) {
this(new CSVReader(fileName, false));
}
public DataSet(CSVReader csvReader) {
loadData(csvReader);
}
public int rowCount() {
return data.size();
}
public List<Double> getRow(int i) {
return data.get(i);
}
private void loadData(CSVReader file) {
while(file.hasNext()) {
List<Double> dbl = convertToDouble(file.getNext());
if(dbl.size()> 0) {
data.add(dbl);
}
}
}
private List<Double> convertToDouble(List<String> next) {
List<Double> dblList = new ArrayList<>(next.size());
for(String item : next) {
try {
dblList.add(Double.parseDouble(item));
}catch (NumberFormatException ex) {
System.err.println("Number format!");
}
}
return dblList;
}
public String toString() {
return data.toString();
}
}



------------------------------------------------------------------------------
COMMENT DOWN FOR ANY QUERY RELATED TO THIS ANSWER,

IF YOU'RE SATISFIED, GIVE A THUMBS UP
~yc~


Related Solutions

JAVA JAVA JAVA Hey i need to find a java code for my homework, this is...
JAVA JAVA JAVA Hey i need to find a java code for my homework, this is my first java homework so for you i don't think it will be hard for you. (basic stuff) the problem: Write a complete Java program The transport Company in which you are the engineer responsible of operations for the optimization of the autonomous transport of liquid bulk goods, got a design contract for an automated intelligent transport management system that are autonomous trucks which...
Hello I need a small fix in my program. I need to display the youngest student...
Hello I need a small fix in my program. I need to display the youngest student and the average age of all of the students. It is not working Thanks. #include <iostream> #include <iomanip> #include <fstream> #include <vector> #include <algorithm> using namespace std; struct Student { string firstName; char middleName; string lastName; char collegeCode; int locCode; int seqCode; int age; }; struct sort_by_age { inline bool operator() (const Student& s1, const Student& s2) { return (s1.age < s2.age); // sort...
I need code written in java for one of my projects the instructions are Write a...
I need code written in java for one of my projects the instructions are Write a program that interacts with the user via the console and lets them choose options from a food menu by using the associated item number. It is expected that your program builds an <orderString> representing the food order to be displayed at the end. (See Sample Run Below). Please note: Each student is required to develop their own custom menus, with unique food categories, items...
Java homework problem: I need the code to be able to have a message if I...
Java homework problem: I need the code to be able to have a message if I type in a letter instead of a number. For example, " Please input only numbers". Then, I should be able to go back and type a number. import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class LoginGui {    static JFrame frame = new JFrame("JFrame Example");    public static void main(String s[]) {        JPanel panel...
Hello i am working on an assignment for my programming course in JAVA. The following is...
Hello i am working on an assignment for my programming course in JAVA. The following is the assignment: In main, first ask the user for their name, and read the name into a String variable. Then, using their name, ask for a temperature in farenheit, and read that value in. Calculate and print the equivalent celsius, with output something like Bob, your 32 degrees farenheit would be 0 degrees celsius Look up the celsius to farenheit conversion if you do...
Hello, I am struggling to understand some of my accounting homework. Question 01 ) Tulsa Company...
Hello, I am struggling to understand some of my accounting homework. Question 01 ) Tulsa Company is considering investing in new bottling equipment and has two options: Option A has a lower initial cost but would require a significant expenditure to rebuild the machine after four years; Option B has higher maintenance costs, but also has a higher salvage value at the end of its useful life. Tulsa’s cost of capital is 11 percent. The following estimates of the cash...
Hello, I need to convert this java array into an array list as I am having...
Hello, I need to convert this java array into an array list as I am having trouble please. import java.util.Random; import java.util.Scanner; public class TestCode { public static void main(String[] args) { String choice = "Yes"; Random random = new Random(); Scanner scanner = new Scanner(System.in); int[] data = new int[1000]; int count = 0; while (!choice.equals("No")) { int randomInt = 2 * (random.nextInt(5) + 1); System.out.println(randomInt); data[count++] = randomInt; System.out.print("Want another random number (Yes / No)? "); choice =...
Hello, I need to do a research and I choose my research question: Do the commercialization...
Hello, I need to do a research and I choose my research question: Do the commercialization and use of civilian drones respect our individual freedoms and privacy? Can you help me with ideas of Research Methodology including: 1. Restatement of research tasks: hypothesis or research questions; 2. Study population and sampling: description of study areas (where? why?), populations and the procedures for the sample selection; 3. Data collection: description of the tools (i.e. the survey instrument) and methods used (i.e....
Hello! I need to present my xml file on the Windows form application I tried but...
Hello! I need to present my xml file on the Windows form application I tried but it dosent work at button 2, I cann't show Xml_file. What is problem here please? have you any suggest or solution . Here is my form code! namespace MyFirstWindos { public partial class Form1 : Form { const string XML1 = "path"; const string XML2 = "Path"; const string ResultFile = "Path"; public Form1() { InitializeComponent(); } private void Run(object sender, EventArgs e)//run button...
Hello, I am having trouble with my Advanced Accounting Ch 18 homework. Accounting for nonprofts. Here...
Hello, I am having trouble with my Advanced Accounting Ch 18 homework. Accounting for nonprofts. Here are a few questions: At the beginning of the year, Nutrition Now, a health and welfare not-for-profit entity, had the following equity balances: Net assets without donor restriction $400,000 Net assets with donor restriction $290,000 1. Unrestricted contributions (pledges) of $250,000, to be collected in cash in thirty days, before the end of the year, are received. 2. Salaries of $27,000 are paid with...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT