SlideShare a Scribd company logo
1 of 8
Download to read offline
For this lab, you will write the following files from scratch, the rest are provided:
AbstractDataCalc
AverageDataCalc
MaximumDataCalc
MinimumDataCalc
MUST USE ALL 6 FILES PROVIDED
AbstractDataCalc is an abstract class, that AverageDataCalc, MaximumDataCalc and
MinimumDataCalc all inherit.
The following files are provided
CSVReader
To help read CSV Files.
DataSet
This file uses CSVReader to read the data into a List> type structure. Think of this as a Matrix
using ArrayLists. The important methods for you are rowCount() and getRow(int i) - Between
CSVReader and DataSet - all your data is loaded for you!
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. However, it will
give you an idea of how the following output is generated.
Sample Input / Output
Given the following CSV file
The output of the provided main is:
Note: the extra line between Set results is optional and not graded. All other spacing must be
exact!
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.
MaximumDataCalc.java------ write code from scratch
Main.java
/*
* Copyright (c) 2020.
* This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike
4.0 International License. To view a copy of this license, visit
http://creativecommons.org/licenses/by-nc-sa/4.0/ or send a letter to Creative Commons, PO Box
1866, Mountain View, CA 94042, USA.
*/
/**
* @author Albert Lionelle
* lionelle@colostate.edu
* Computer Science Department
* Colorado State University
* @version 20200624
*/
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);
}
}
MinumumDataCalc.java------ write code from scratch
AverageDataCalc.java------ write code from scratch
AbstractDataCalc.java------ write code from scratch
DataSet.java
import java.util.ArrayList;
import java.util.List;
/**
* A simple container that holds a set of Data, by row/col (matrix)
* @version 20200627
*/
public class DataSet {
private final List> data = new ArrayList<>();
/**
* Reads the file, assuming it is a CSV file
* @param fileName name of file
*/
public DataSet(String fileName) {
this(new CSVReader(fileName, false));
}
/**
* Takes in a CSVReader to load the dataset
* @param csvReader a csvReader
*/
public DataSet(CSVReader csvReader) {
loadData(csvReader);
}
/**
* Returns the number of rows in the data set
* @return number of rows
*/
public int rowCount() {
return data.size();
}
/**
* Gets a specific row based on the index. Throws exception if out of bounds
* @param i the index of the row
* @return the row as a List of doubles
*/
public List getRow(int i) {
return data.get(i);
}
/**
* Loads the data from th CSV file
* @param file a CSVReader
*/
private void loadData(CSVReader file) {
while(file.hasNext()) {
List dbl = convertToDouble(file.getNext());
if(dbl.size()> 0) {
data.add(dbl);
}
}
}
/**
* Converts a List of strings to a list of doubles. Ignores non-doubles in the list
* @param next a List of strings
* @return a List of doubles
*/
private List convertToDouble(List next) {
List 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;
}
/**
* Simple way to view the data
* @return a String of the
*/
@Override
public String toString() {
return data.toString();
}
}
CSVReader.java
/*
* Copyright (c) 2020.
* This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike
4.0 International License. To view a copy of this license, visit
http://creativecommons.org/licenses/by-nc-sa/4.0/ or send a letter to Creative Commons, PO Box
1866, Mountain View, CA 94042, USA.
*/
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* This is a slightly more advanced CSV reader that can handle quoted tokens.
*/
public class CSVReader {
private static final char DELIMINATOR = ',';
private Scanner fileScanner;
/**
* Basic constructor that assumes the first line should be skipped.
* @param file name of file to read
*/
public CSVReader(String file) {
this(file, true);
}
/**
* A constructor that requires the name of the file to open
* @param file filename to read
* @param skipHeader true to skip header, false if it is to be read
*/
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);
}
}
/**
* Reads a line (nextLine()) and splits it into a String array by the DELIMINATOR, if the line is
* empty it will also return null. This is the proper way to check for CSV files as compared
* to string.split - as it allows for "quoted" strings ,",",.
* @return a String List if a line exits or null if not
*/
public List getNext() {
if(hasNext()){
String toSplit = fileScanner.nextLine();
List 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;
}
/**
* Checks to see if the fileScanner has more lines and returns the answer.
* @return true if the file scanner has more lines (hasNext())
*/
public boolean hasNext() {
return (fileScanner != null) && fileScanner.hasNext();
}
}

More Related Content

Similar to For this lab, you will write the following files from scratch, the r.pdf

Getting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfGetting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
info309708
 
In this lab, we will write an application to store a deck of cards i.pdf
In this lab, we will write an application to store a deck of cards i.pdfIn this lab, we will write an application to store a deck of cards i.pdf
In this lab, we will write an application to store a deck of cards i.pdf
contact41
 
Frequency .java Word frequency counter package frequ.pdf
Frequency .java  Word frequency counter  package frequ.pdfFrequency .java  Word frequency counter  package frequ.pdf
Frequency .java Word frequency counter package frequ.pdf
arshiartpalace
 
import java.io.BufferedReader;import java.io.BufferedWriter;.docx
import java.io.BufferedReader;import java.io.BufferedWriter;.docximport java.io.BufferedReader;import java.io.BufferedWriter;.docx
import java.io.BufferedReader;import java.io.BufferedWriter;.docx
wilcockiris
 
30 5 Database Jdbc
30 5 Database Jdbc30 5 Database Jdbc
30 5 Database Jdbc
phanleson
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
phanleson
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
leminhvuong
 

Similar to For this lab, you will write the following files from scratch, the r.pdf (20)

Algorithms devised for a google interview
Algorithms devised for a google interviewAlgorithms devised for a google interview
Algorithms devised for a google interview
 
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfGetting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
 
In this lab, we will write an application to store a deck of cards i.pdf
In this lab, we will write an application to store a deck of cards i.pdfIn this lab, we will write an application to store a deck of cards i.pdf
In this lab, we will write an application to store a deck of cards i.pdf
 
Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
 
Jdbc tutorial
Jdbc tutorialJdbc tutorial
Jdbc tutorial
 
spring-tutorial
spring-tutorialspring-tutorial
spring-tutorial
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Frequency .java Word frequency counter package frequ.pdf
Frequency .java  Word frequency counter  package frequ.pdfFrequency .java  Word frequency counter  package frequ.pdf
Frequency .java Word frequency counter package frequ.pdf
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
 
Aggregate.pptx
Aggregate.pptxAggregate.pptx
Aggregate.pptx
 
Spring data ii
Spring data iiSpring data ii
Spring data ii
 
Stata Programming Cheat Sheet
Stata Programming Cheat SheetStata Programming Cheat Sheet
Stata Programming Cheat Sheet
 
import java.io.BufferedReader;import java.io.BufferedWriter;.docx
import java.io.BufferedReader;import java.io.BufferedWriter;.docximport java.io.BufferedReader;import java.io.BufferedWriter;.docx
import java.io.BufferedReader;import java.io.BufferedWriter;.docx
 
30 5 Database Jdbc
30 5 Database Jdbc30 5 Database Jdbc
30 5 Database Jdbc
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
Hadoop Integration in Cassandra
Hadoop Integration in CassandraHadoop Integration in Cassandra
Hadoop Integration in Cassandra
 
Stata cheatsheet programming
Stata cheatsheet programmingStata cheatsheet programming
Stata cheatsheet programming
 
ADO.NET
ADO.NETADO.NET
ADO.NET
 
Android database tutorial
Android database tutorialAndroid database tutorial
Android database tutorial
 

More from alokindustries1

Select one of the scenarios listed below and explain the best soluti.pdf
Select one of the scenarios listed below and explain the best soluti.pdfSelect one of the scenarios listed below and explain the best soluti.pdf
Select one of the scenarios listed below and explain the best soluti.pdf
alokindustries1
 

More from alokindustries1 (20)

Select the TRUE statement Group of answer choicesA. An arthropod�.pdf
Select the TRUE statement Group of answer choicesA. An arthropod�.pdfSelect the TRUE statement Group of answer choicesA. An arthropod�.pdf
Select the TRUE statement Group of answer choicesA. An arthropod�.pdf
 
Select one of the scenarios listed below and explain the best soluti.pdf
Select one of the scenarios listed below and explain the best soluti.pdfSelect one of the scenarios listed below and explain the best soluti.pdf
Select one of the scenarios listed below and explain the best soluti.pdf
 
Select the combination of the following statements relating to sourc.pdf
Select the combination of the following statements relating to sourc.pdfSelect the combination of the following statements relating to sourc.pdf
Select the combination of the following statements relating to sourc.pdf
 
select each of the following which relate to the term homozygous .pdf
select each of the following which relate to the term homozygous  .pdfselect each of the following which relate to the term homozygous  .pdf
select each of the following which relate to the term homozygous .pdf
 
Select the combination of the following statements regarding stakeho.pdf
Select the combination of the following statements regarding stakeho.pdfSelect the combination of the following statements regarding stakeho.pdf
Select the combination of the following statements regarding stakeho.pdf
 
select each of the following which relate to the term heterozygous.pdf
select each of the following which relate to the term heterozygous.pdfselect each of the following which relate to the term heterozygous.pdf
select each of the following which relate to the term heterozygous.pdf
 
Select all that are true regarding Economic Value Added (EVA) a) .pdf
Select all that are true regarding Economic Value Added (EVA) a) .pdfSelect all that are true regarding Economic Value Added (EVA) a) .pdf
Select all that are true regarding Economic Value Added (EVA) a) .pdf
 
Select the case that would most likely be filed under disparate impa.pdf
Select the case that would most likely be filed under disparate impa.pdfSelect the case that would most likely be filed under disparate impa.pdf
Select the case that would most likely be filed under disparate impa.pdf
 
Select all that are true about plasmid DNA.a.The DNA in plasmids.pdf
Select all that are true about plasmid DNA.a.The DNA in plasmids.pdfSelect all that are true about plasmid DNA.a.The DNA in plasmids.pdf
Select all that are true about plasmid DNA.a.The DNA in plasmids.pdf
 
Select a current event (local or international) that is relevant to .pdf
Select a current event (local or international) that is relevant to .pdfSelect a current event (local or international) that is relevant to .pdf
Select a current event (local or international) that is relevant to .pdf
 
Seleccione SOLO UNO de los siguientes Objetivos de Desarrollo Sosten.pdf
Seleccione SOLO UNO de los siguientes Objetivos de Desarrollo Sosten.pdfSeleccione SOLO UNO de los siguientes Objetivos de Desarrollo Sosten.pdf
Seleccione SOLO UNO de los siguientes Objetivos de Desarrollo Sosten.pdf
 
Seleccione todas las cualidades que pertenecen a los sistemas parlam.pdf
Seleccione todas las cualidades que pertenecen a los sistemas parlam.pdfSeleccione todas las cualidades que pertenecen a los sistemas parlam.pdf
Seleccione todas las cualidades que pertenecen a los sistemas parlam.pdf
 
Seleccione la declaraci�n FALSA de las siguientes A. Trabajar con o.pdf
Seleccione la declaraci�n FALSA de las siguientes A. Trabajar con o.pdfSeleccione la declaraci�n FALSA de las siguientes A. Trabajar con o.pdf
Seleccione la declaraci�n FALSA de las siguientes A. Trabajar con o.pdf
 
Seismic waves travel faster when the rock is less stiff.A) TrueB.pdf
Seismic waves travel faster when the rock is less stiff.A) TrueB.pdfSeismic waves travel faster when the rock is less stiff.A) TrueB.pdf
Seismic waves travel faster when the rock is less stiff.A) TrueB.pdf
 
Seg�n TCPS 2, �qu� es la investigaci�n de riesgo m�nimo (seleccione .pdf
Seg�n TCPS 2, �qu� es la investigaci�n de riesgo m�nimo (seleccione .pdfSeg�n TCPS 2, �qu� es la investigaci�n de riesgo m�nimo (seleccione .pdf
Seg�n TCPS 2, �qu� es la investigaci�n de riesgo m�nimo (seleccione .pdf
 
Seg�n Juan Linz (1990), �c�mo los sistemas presidenciales crean disc.pdf
Seg�n Juan Linz (1990), �c�mo los sistemas presidenciales crean disc.pdfSeg�n Juan Linz (1990), �c�mo los sistemas presidenciales crean disc.pdf
Seg�n Juan Linz (1990), �c�mo los sistemas presidenciales crean disc.pdf
 
Seg�n Holton en la fuente 1, �cu�les fueron los motivos de los padre.pdf
Seg�n Holton en la fuente 1, �cu�les fueron los motivos de los padre.pdfSeg�n Holton en la fuente 1, �cu�les fueron los motivos de los padre.pdf
Seg�n Holton en la fuente 1, �cu�les fueron los motivos de los padre.pdf
 
Seg�n el texto, �qu� es un factor Persona a la que se le da autori.pdf
Seg�n el texto, �qu� es un factor  Persona a la que se le da autori.pdfSeg�n el texto, �qu� es un factor  Persona a la que se le da autori.pdf
Seg�n el texto, �qu� es un factor Persona a la que se le da autori.pdf
 
Security X has an actual rate of return of 11.8 and a beta of 0.72..pdf
Security X has an actual rate of return of 11.8 and a beta of 0.72..pdfSecurity X has an actual rate of return of 11.8 and a beta of 0.72..pdf
Security X has an actual rate of return of 11.8 and a beta of 0.72..pdf
 
Seg�n el C�digo y las Normas, �cu�l de las siguientes afirmaciones c.pdf
Seg�n el C�digo y las Normas, �cu�l de las siguientes afirmaciones c.pdfSeg�n el C�digo y las Normas, �cu�l de las siguientes afirmaciones c.pdf
Seg�n el C�digo y las Normas, �cu�l de las siguientes afirmaciones c.pdf
 

Recently uploaded

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Recently uploaded (20)

Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 

For this lab, you will write the following files from scratch, the r.pdf

  • 1. For this lab, you will write the following files from scratch, the rest are provided: AbstractDataCalc AverageDataCalc MaximumDataCalc MinimumDataCalc MUST USE ALL 6 FILES PROVIDED AbstractDataCalc is an abstract class, that AverageDataCalc, MaximumDataCalc and MinimumDataCalc all inherit. The following files are provided CSVReader To help read CSV Files. DataSet This file uses CSVReader to read the data into a List> type structure. Think of this as a Matrix using ArrayLists. The important methods for you are rowCount() and getRow(int i) - Between CSVReader and DataSet - all your data is loaded for you! 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. However, it will give you an idea of how the following output is generated. Sample Input / Output Given the following CSV file The output of the provided main is: Note: the extra line between Set results is optional and not graded. All other spacing must be exact! 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,
  • 2. 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. MaximumDataCalc.java------ write code from scratch Main.java /* * Copyright (c) 2020. * This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/4.0/ or send a letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, USA. */ /** * @author Albert Lionelle * lionelle@colostate.edu
  • 3. * Computer Science Department * Colorado State University * @version 20200624 */ 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); } } MinumumDataCalc.java------ write code from scratch AverageDataCalc.java------ write code from scratch AbstractDataCalc.java------ write code from scratch DataSet.java import java.util.ArrayList; import java.util.List; /** * A simple container that holds a set of Data, by row/col (matrix) * @version 20200627 */ public class DataSet { private final List> data = new ArrayList<>();
  • 4. /** * Reads the file, assuming it is a CSV file * @param fileName name of file */ public DataSet(String fileName) { this(new CSVReader(fileName, false)); } /** * Takes in a CSVReader to load the dataset * @param csvReader a csvReader */ public DataSet(CSVReader csvReader) { loadData(csvReader); } /** * Returns the number of rows in the data set * @return number of rows */ public int rowCount() { return data.size(); } /** * Gets a specific row based on the index. Throws exception if out of bounds * @param i the index of the row * @return the row as a List of doubles */ public List getRow(int i) { return data.get(i); } /** * Loads the data from th CSV file * @param file a CSVReader */ private void loadData(CSVReader file) { while(file.hasNext()) { List dbl = convertToDouble(file.getNext());
  • 5. if(dbl.size()> 0) { data.add(dbl); } } } /** * Converts a List of strings to a list of doubles. Ignores non-doubles in the list * @param next a List of strings * @return a List of doubles */ private List convertToDouble(List next) { List 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; } /** * Simple way to view the data * @return a String of the */ @Override public String toString() { return data.toString(); } } CSVReader.java /* * Copyright (c) 2020. * This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. To view a copy of this license, visit
  • 6. http://creativecommons.org/licenses/by-nc-sa/4.0/ or send a letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, USA. */ import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * This is a slightly more advanced CSV reader that can handle quoted tokens. */ public class CSVReader { private static final char DELIMINATOR = ','; private Scanner fileScanner; /** * Basic constructor that assumes the first line should be skipped. * @param file name of file to read */ public CSVReader(String file) { this(file, true); } /** * A constructor that requires the name of the file to open * @param file filename to read * @param skipHeader true to skip header, false if it is to be read */ 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); } } /**
  • 7. * Reads a line (nextLine()) and splits it into a String array by the DELIMINATOR, if the line is * empty it will also return null. This is the proper way to check for CSV files as compared * to string.split - as it allows for "quoted" strings ,",",. * @return a String List if a line exits or null if not */ public List getNext() { if(hasNext()){ String toSplit = fileScanner.nextLine(); List 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; } /** * Checks to see if the fileScanner has more lines and returns the answer. * @return true if the file scanner has more lines (hasNext()) */ public boolean hasNext() { return (fileScanner != null) && fileScanner.hasNext(); }
  • 8. }