Question
Could you give me explanations or ideas on my recent java homework ? The homework has three part and I already have part1 done .
Could you give me explanations or ideas on my recent java homework ? The homework has three part and I already have part1 done . Please help on Part2 and Part3. Please look at the instruction and files below. You need to put all files : VirusTracker.java; CSV.java; Aggregator.java; Grouping.java; Sample.java; Common.java;aggCfg.txt and baCfg.txt in one folder first, and edit VirusTracker.java; CSV.java; Aggregator.java; Grouping.java. Common.java and Sample.java may be need to be edited if possible. Thanks !
Part2's instruction :
Define an Aggregator class instance method add() with this profile:
Header: public void add (ArrayList
Summary: dbRec represents the comma separated values in one line of a CSV file.
add() is called from CSV.update() when update() determines that the Aggregator
object should add the values in a DB record to its totals.
Details:
if this.samples.size() == 0, add() uses dbRec to create the first Sample object on this.samples.
else if the date in dbRec is more recent than that of the last entry on this.samples, add() uses dbRec to make a new Sample object and append it to this.samples.
else if the date in dbRec is the same as the date in the last entry on this.samples, add() uses dbRec to update the totals of the last Sample object on this.samples.
else add() prints a warning saying that a decreasing date was found in the
DB, and continues.
(You need to work on Aggregator.java)
Define a CSV class instance method with this profile:
Header: public void update()
Summary: update() calls the add method of the Aggregator objects referenced through this.aFilter, passing this.curFields as an argument (see above); and the add() method of the Grouping objects referenced through this.bFilter.
Details:
update() always calls the add method of the Terra Aggregator.
update() will call theadd method of the US Aggregator if this.curFields.get(COUNTRY) = "US",and the add method of the Canada Aggregator if this.curFields.get(COUNTRY) = "Canada."
update() will call theadd method of the California Aggregator if this.curFields.get(PROVINCE) = "California".
if this.curFields.get(County) is a key in this.bFilter, update() will call theadd method of the Bay Area Aggregator, and then the add method of the appropriate Grouping in this.bFilter.
(You need to work on CSV.java and other if possible)
.Make a public class called VirusTracker, which uses the makeNextFileName() method you wrote in part 1 to open the CSV filenames for an analysis interval.After configuring the Aggregator and Grouping objects, process the CSV files named by makeNextFileName, skipping the header line and then calling CSV.update() to process the rest of the file.
(you need to work on VirusTracker.java)
Part3's instruction :
Define toString() methods for the Aggregator and Grouping classes, which
will return the following information in String form (note that most
of the informations comes from the Grouping object's samples ArrayList):
The name of the Grouping or Aggregator object (for example,
"Napa" or "Terra")
The start and end dates of the analysis interval.
The starting and ending infection rate (define as case count/population,
expressed as a percentage)
The starting and ending case counts and deceased counts.
The case count and deceased count compound daily growth rate over the
analysis interval expressed as a percentage
(the Grouping methodCompoundDailyGrowthRate will do the calculation).
The Case count and deceased count time to double, based on the
starting and ending values in the analysis intervals.The formula is:
log10(2)/log10(1+(percent/100))
where "percent" is the output of CompoundDailyGrowthRate(()
Add logic to the end of main() in VirusTracker() (see part 2
above) that uses the toString methods to display the stats
accumulated for the Grouping and Aggregator objects.
(You need to work on Aggregator.java; Grouping.java and VirusTracker.java)
Part 1's code- makeNextFileName.java: (no need to edit, but should be used as an instance method in TrackerVirus.java as the part 2's instructions above described)
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Scanner;
import java.time.format.DateTimeParseException;
public class makeNextFileName {
private static Scanner KeyInputter = null;
private static LocalDate useDate = null;
private static LocalDate baseDate = null;
private static int howManyDays = 1;
private static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM-dd-yyyy");
public static void main(String...args) {
KeyInputter = new Scanner(System.in);
try {
String strStaringDate;
String strHowManyDays;
while(true){
strStaringDate= getInputValue("Enter the starting date of the analysis interval [MM-DD-YYYY] ");
if(strStaringDate.isEmpty()){
System.out.println("Dont be silence!");
continue;
}
try {
useDate = LocalDate.parse(strStaringDate, dateFormatter);
baseDate = LocalDate.parse(strStaringDate, dateFormatter);
} catch (DateTimeParseException e) {
System.out.println("Oops! " +strStaringDate+" is not correct format, please try again!!");
System.out.println("You got an error. The error type is " +e.getClass().getName() + " and the actual problem was: " + e.getMessage());
continue;
}
break;
}
while(true){
strHowManyDays= getInputValue("Enter how many days for the analysis interval");
if(strHowManyDays.isEmpty()){
System.out.println("Dont be silence!");
continue;
}
try {
howManyDays = Integer.parseInt(strHowManyDays);
if(howManyDays<0){
System.out.println("Oops! No negative number allowed, please try again !");
continue;
}
} catch (NumberFormatException e) {
System.out.println("Oops! You got an error. The error type is "
+e.getClass().getName() + " and the actual problem was: "
+ e.getMessage()+". Please try again !");
continue;
}
break;
}
} catch (DateTimeParseException e) {
System.out.println("Oops! You got an error. The error type is " +
e.getClass().getName() + " and the actual problem was: " + e.getMessage());
System.exit(-1);
}
String lastFileName = "";
while (lastFileName != null) {
lastFileName = makeNextFileName();
if (lastFileName != null) { System.out.println(
lastFileName); }
}
KeyInputter.close();
}
public static String makeNextFileName() {
long daysBetween = ChronoUnit.DAYS.between(baseDate, useDate) + 1;
if (daysBetween > howManyDays) {
return null;
}
String returnValue = useDate.format(dateFormatter) + ".csv";
useDate = useDate.plusDays((long)1);
return returnValue;
}
private static String getInputValue(String promptValue) {
System.out.print(promptValue + ": ");
return KeyInputter.nextLine();
}
}
VirusTracker.java: (need to be edited)
import java.util.Scanner;
import java.util.Calendar;
public class VirusTracker {
int mm;
int dd;
int yyyy;
int daysInAnalysisInterval;
int curDayInAnalysisInterval;
public VirusTracker()
{yyyy = Common.INVALID_DATE_FIELD; this.curDayInAnalysisInterval = 0;}
/*
* Output filename in the form MM-DD-YYYY.csv
*/
public String makeNextFileName() {
return Common.NULL_STRING;
}//makeNextFileName()
public static void main(String []args) {
VirusTracker vt = new VirusTracker();
String csvFn = vt.makeNextFileName();
do {
csvFn = vt.makeNextFileName();
if (csvFn.equals(Common.NULL_STRING)) { break; }
System.out.printf("Trace: %s ",csvFn);
CSV csv = new CSV(csvFn);
csv.getLine();//we will skip past the header
/*
* For every line in the CSV after the header:
*1.Parse that line into the comma separated value
*fields
*2.Ask CSV.update() to use the CSV fields to update
*all the configured Aggregator and Grouping
*objects.
*
*/
while (!csv.eof() ) {
csv.getLine();
csv.parseFields();
//update configured Aggregator & Grouping objects
csv.update();
} //process every line in the file.
csv.close(); //be good citizens and close the file when done
} while (!csvFn.equals(Common.NULL_STRING));
/*
* Is use the Aggregator.toString() and Grouping.toString()
* methods, which you will write for this homework, to
* display the accumulated stats.
*/
}//main()
} //class VirusTracker
CSV.java : (need to be edited)
import java.util.Calendar;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Scanner;
import java.util.Enumeration;
import java.io.*;
//Functinality associated with a CSV file
// CSV Comma Separated Value, convention for
//exporting a spreadsheet or a DB into a text file.
public class CSV {
public static final String FILENAME_EXTENSION = ".csv";
public static final int FIPS = 0;//provided by JHU, for what?
public static final int COUNTY = 1;
public static final int PROVINCE = 2;
public static final int COUNTRY = 3;
public static final int LAST_UPDATE = 4;
public static final int LATITUDE = 5;
public static final int LONGTITUDE = 6;
public static final int CONFIRMED = 7;
public static final int DECEASED = 8;
public static final int RECOVERED = 9;
public static final int ACTIVE = 10;
public static final int FULL_NAME = 11;
public static final int LAST_FIELD = FULL_NAME;
static int numFiles = 0;//tracks the number of CSV object created
// *** *** ***Start CSV Instance variables *** *** ***
String fileName;// Name of the file
int fileNumber;// The ID of the CSV object
Scanner csvFile;//Actual file we will read from
String curLine;//Current line we're processing
ArrayList
ArrayList
ArrayList
//A Hashtable object is a collection of key/value pairs, where the
// keys are unique.bFilter and aFilter allow us to track Groupings
// and Aggregates by name.
Hashtable
Hashtable
// *** *** ***End CSV Instance variables *** *** ***
private void initRefInstanceData() {
this.curFields = new ArrayList
this.bNames = new ArrayList
this.aNames = new ArrayList
this.aFilter = new Hashtable
this.bFilter = new Hashtable
}// initRefInstanceData()
/*
*In practice we would expect to read the next line from
*the CSV file, but this is useful in testing
*/
public void setLine(String line_) {
this.curLine = line_;
} //setLine()
/*
* Read next line from CSV file
*/
public String getLine() {
//Call the Scanner .nextLine() instance method to get the next
// file from a file
this.curLine = this.csvFile.nextLine();
return this.curLine;
} //getLine()
public boolean eof() {
return !this.csvFile.hasNext();
} //eof()
public void close() {
this.csvFile.close();
} //close()
/*
* Parses this.curLine into this.curFields,
* a vector of
* comma delimited fieldsAccount for
* commas embeded in quotes
*
*/
public ArrayList
this.curFields.clear();
String []quotesArray = this.curLine.split(Common.QUOTE);
for (int idx = 0; idx < quotesArray.length; ++idx) {
if (idx %2 == 0) {
String []commaArray = quotesArray[idx].split(Common.COMMA);
for (int cIdx = 0; cIdx < commaArray.length; ++cIdx) {
this.curFields.add(commaArray[cIdx]);
} //inner for
} //if unquoted section
else {
this.curFields.add(Common.QUOTE + quotesArray[idx] +
Common.QUOTE);
} //else
} //for
return this.curFields;
} //parseFields()
public static String profile (ArrayList
String fmtStr =
"DB record profile: Country: %s; Province: %s; County: %s ";
String s=
String.format(fmtStr,f.get(COUNTRY),f.get(PROVINCE),f.get(COUNTY));
fmtStr = "%sUpdated: %s; Longtitude: %s; Latitude: %s ";
s = String.format(fmtStr,s,f.get(LAST_UPDATE),f.get(LONGTITUDE),
f.get(LATITUDE));
fmtStr = "%sCon.: %s; Dec: %d; Recov: %d; Active%d ";
s = String.format(fmtStr,s,f.get(CONFIRMED),f.get(DECEASED),
f.get(RECOVERED), f.get(ACTIVE) );
s = String.format("%sFull name: %s ",s,f.get(FULL_NAME));
return s;
} //profile()
public static String getDBRecDate(ArrayList
String []timeStamp = fields.get(CSV.LAST_UPDATE).split(" ");
if (timeStamp.length == 2) { return timeStamp[0]; }
else {
String s =
"*** Program Failure! Date note found in DB record ***";
System.out.println(s);
profile(fields);
System.exit(Common.PROGRAM_FAILURE);
return Common.NULL_STRING; //keep the compiler happy
} //else program failure
} //getDBRecDate()
public String toString() {
String description = Common.NULL_STRING;
description = String.format("File name: \"%s\" ",this.fileName);
description = String.format("%sCurrent line: \"%s\" ",
description,this.curLine);
for (int idx = 0; idx < this.curFields.size(); ++idx) {
description += String.format("%d. %s ",
idx, this.curFields.get(idx));
} //for
return description;
} //toString()
/*
*baFileName is the name of the Bay Area config file
*aggFileName is the name of the Aggregates config file
*For lab #5, complete the config method to load the names of the
*Bay Area counties into bNames; the Grouping objects for the
*Bay Area counties into bFilter;the names of the aggregators" into
*aNames; and the Aggregator objects for the aggregators into aFilter
*/
public void config(String baFileName, String aggFileName) throws IOException {
//Configure Groupings (Bay Area Counties)
Scanner baFile = new Scanner(new FileInputStream( baFileName ));
//Initialize variables updated in loop
long baPopulation = 0; //keep a running total of Bay Area population
long population;//population of a single county
String countyName = Common.NULL_STRING;
// *** *** *** *** Start part to be completed for LAB *** *** ***
while (baFile.hasNext()) {
countyName = baFile.nextLine();//Read the next line from baFile
bNames.add(countyName);//add countyName tobNames;
population = baFile.nextLong();//Read the county's population
baPopulation += population;//update baPopulation
// county name key, value Grouping object
Grouping county= new Grouping(countyName, Common.CA, Common.US,
0.0, 0.0, population);
this.bFilter.put(countyName,county);
baFile.nextLine(); //go to next line by reading past newline char
} //while reading records from BA file
baFile.close();
//Configure Aggregators
Scanner aggFile = new Scanner(new FileInputStream(aggFileName ));
String aggName;
long aggPopulation;
Aggregator agg, terra=null, us=null, ca=null;
while (aggFile.hasNext() ) {
aggName = aggFile.nextLine();
aNames.add(aggName);
aggPopulation = aggFile.nextLong();
aggFile.nextLine(); //skip past line break
switch(aggName) {
case Common.TERRA:
//we count on Terra being 1st config file
terra = new Aggregator(Common.TERRA,aggPopulation);
agg = terra;
break;
case Common.US:
//we count on the US coming before CA in the config file
us = new Aggregator(terra,aggPopulation,Common.TERRA,
Common.NULL_STRING,aggName);
agg = us;
break;
case Common.CANADA:
agg =new Aggregator(terra,aggPopulation,Common.TERRA,
Common.NULL_STRING,aggName);
break;
case Common.CA:
//We count on California coming before the Bay Area
// in the config file.
ca =new Aggregator(us,aggPopulation,Common.TERRA,
Common.NULL_STRING,Common.US,aggName);
agg = ca;
break;
case Common.BA:
agg =new Aggregator(ca,baPopulation,Common.TERRA,aggName);
break;
default:
//Assume it's a state
agg =new Aggregator(us,aggPopulation,Common.TERRA,
Common.NULL_STRING,Common.US,aggName);
} //switch
this.aFilter.put(aggName,agg);
} //while
// *** *** *** *** End part to be completed for LAB *** *** ***
} //config for Bay Area and aggregates
void showFilters() {
System.out.println("Bay Area county Filter");
for (int idx = 0; idx < this.bNames.size(); ++ idx ) {
String bName = this.bNames.get(idx);
System.out.printf("%s County, population %d ",
bName,this.bFilter.get(bName).getPopulation() );
} //for loop
System.out.println("Aggregator Filter");
for (int idx = 0; idx < this.aNames.size(); ++ idx ) {
String aName = this.aNames.get(idx);
System.out.printf("Aggregator %s, population %d ",
aName,this.aFilter.get(aName).getPopulation() );
} //for loop
/*
* Display in random order
* Enumeration aEnum = this.aFilter.keys();
* while (aEnum.hasMoreElements() ) {
*String name = (String) aEnum.nextElement();
*} //while()
*/
}//showFilters()
//Access this.curFields for the Db rec
public static Sample makeSample() {
Sample sample = new Sample(
return null;
} //makeSample()
/*
*Use the current DB record to update all the Grouping and
*Aggregate objects for which you are collecting data.
*That DB record is divided up into comma separated fields,
*and stored this.curFields.
*For example, suppose the line were:
*6075,San Francisco,California,US,2020-04-13 23:07:54,
*37.75215114,-122.43856720000001,957,15,0,942,
*"San Francisco, California, US"
*We want to do 4 updates:
*0.Update the 4/13 totals for Terra
*0.5 Updat the 4/13 totals for the US
*1.Update the 4/13 totals for California
*2.Update the 4/13 totals for our Bay Area counties
*3.SF is a Grouping, not an Aggregator, so it has
*only one sample per day.Add that sample to the
*SF Grouping object.
*/
void update() {
//For every record we read we want to update the totals for
// for Terra, planet Earth
//Aggregator objectvalue.add(DB rec)
this.aFilter.get(Common.TERRA).add(this.curFields);
//store the country field in the DB record in a seperate var
String country = this.curFields.get(CSV.COUNTRY);
if (this.aFilter.containsKey(country) ) {
//add the totals in the DB rec parseFielsds to the
//country referenced through aFilter
this.aFilter.get(country).add(this.curFields);
} //add totals to country
String province = this.curFields.get(CSV.PROVINCE);
if (this.aFilter.containsKey(province) ) {
//add the totals in the DB rec parseFielsds to the
//country referenced through aFilter
this.aFilter.get(province).add(this.curFields);
} //add totals to province
//Two things remain to be done in CSV.update()
//1. update the Bay Area Aggregator
//2. update the couty grouping
String county = this.curFields.get(CSV.COUNTY);
//how can tell that we have Bay Area updates to do?
if ( this.bFilter.containsKey(county)) {
//update the Bay Area Aggregator
this.aFilter.get(Common.BA).add(this.curFields);
//update the Grouping object for the county
Sample sample = makeSample(); //make a Sample based on the DB rec
this.bFilter.get(county).add(sample); //add sample to county Grouping object
} //if it's a Bay area county
return;
} //CSV.update()
/*
* Useful construtcor for testing
*/
public CSV () {
this.fileName = "UNOPENED";
this.curLine = Common.NULL_STRING;
this.initRefInstanceData();
} //useful testing constructor
/*
* In practice, we would typically want to construct
* a CSV object by opening a file
*/
public CSV(String fileName_) throws IOException {
this.fileName = fileName_;
this.csvFile = newScanner(new FileInputStream(this.fileName));
//set fileNumber and increment static class variable
this.fileNumber = CSV.numFiles++;
this.curLine = Common.NULL_STRING;
this.initRefInstanceData();
} //practical CSV constructor
static void stop() {System.exit(0); }
public static void main(String []args) throws IOException {
System.out.println("*** Start CSV class unit test ***");
CSV csv = new CSV();
csv.config(Common.baCfgFileName, Common.aggCfgFileName);
csv.showFilters();
stop();
Hashtable
Calendar today = Calendar.getInstance();
long ms = Common.calToMillis(today);
String todayStr = Common.calToYYYYMMDD_hhmmss(today);
Sample s = new Sample(4,1,1,3,ms,todayStr);
otherSamples.put("sample 1", s);
System.out.printf("confirm count: %d ",
otherSamples.get("sample 1").getC());
//test with line from Johns Hopkins DB
//the country could be "Korea, South", and you want to parse
// that as a single field.
csv.setLine("San Francisco,California,US,2020-04-13 23:07:54," +
"37.75215114,-122.43856720000001,957,15,0,942" +
"\"San Francisco, California, US\"");
csv.parseFields();//does nothing until you add the needed logic
System.out.println(csv);
//below is not neeed for lab #6, it's just FYI to show where we're headed.
csv = new CSV("04-13-2020.csv");
for (int idx = 0; idx < 5; ++idx) {
if (csv.eof()){break;}
System.out.printf("%d%s ",idx,csv.getLine());
} //for
csv.close();
//cfg(Common.baCfgFileName,Common.aggCfgFileName);
System.out.println("*** End CSV class unit test ***");
} //main()
} //class CSV
Aggregator.java : (need to be edited)
import java.util.ArrayList;
public class Aggregator extends Grouping{
ArrayList
ArrayList
String planet;
String region;
Aggregator parent;
/*
*Merge data from DB record into an Aggregator object
*/
void add (ArrayList
} //add()
void efface(Aggregator agg) {
agg.planet = Common.NULL_STRING;
agg.region = Common.NULL_STRING;
} //efface()
Aggregator(String planet) {
super(); efface(this);
this.parent = null;
this.planet = planet;
} //Constructor
Aggregator(String planet, long pop) {
super(); efface(this);
this.parent = null;
this.planet = planet;
this.population = pop;
} //Constructor
Aggregator(Aggregator parent, long pop, String planet,
String region) {
super();
this.parent = parent;
this.population = pop;
this.planet = planet;
this.region = region;
} //Constructor
Aggregator(Aggregator parent, long pop, String planet,
String region, String country) {
super();
this.parent = parent;
this.population = pop;
this.planet = planet;
this.region = region;
this.country = country;
} //Constructor
Aggregator(Aggregator parent, long pop, String planet,
String region, String country, String province) {
super();
this.parent = parent;
this.population = pop;
this.planet = planet;
this.region = region;
this.country = country;
this.province = province;
} //Constructor
public String toString() {
return Common.NULL_STRING;
} //Aggregator.toString()
public static void main (String []args) {
System.out.println("*** Start Aggregate class unit test ***");
System.out.println("*** End Aggregate class unit test ***");
} //main()
} //class Aggregate
Common.java : (might or might not need to be edited, but associated with CSV.java)
import java.util.Calendar;
public class Common {
public static final String NULL_STRING = "";
public static final StringBLANK = " ";
public static final StringCOLON = ":";
public static final StringCOMMA = ",";
public static final StringDASH = "-";
public static final StringDOT = ".";
public static final StringQUOTE = "\"";
public static final StringSLASH = "/";
publicstatic final int INVALID_DATE_FIELD = -1;
public static final boolean TRACE = false;
public static final int IO_FAILURE = 8;
public static final int CSV_FILE_ISSUE =5000;
public static final int PROGRAM_FAILURE = 6000;
public static final int DB_ERROR = 0;
public static final char CONFIRMED = 'C';
public static final char DECEASED = 'D';
public static final String baCfgFileName= "baCfg.txt";
public static final String aggCfgFileName = "aggCfg.txt";
public static final String BA = "Bay Area";
public static final String CA = "California";
public static final String CANADA = "Canada";
public static final String TERRA = "Terra";
public static final String US = "US";
public static void trace(String s) {trace(s,false); }
public static void trace(String s, boolean b){
if (b) { System.out.println(s); }
}
//get back something like 2020-04-20 08:53:48
public static String calToYYYYMMDD_hhmmss(Calendar cal){
String tStr = String.format("Common.calToYYYYMMDD_hhmmss(): %d ",
cal.get(Calendar.MONTH) );
trace(tStr,true);
String dateTimeStr = String.format("%d-%02d-%02d %02d:%02d:%02d",
cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH),cal.get(Calendar.HOUR_OF_DAY),
cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND) );
return dateTimeStr;
} //YYMMDD_hhmmss()
public static String MMDDYYYY_hhmmss(Calendar cal){
String dateTimeStr = String.format("%02d-%02d-%d %02d:%02d:%02d",
cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH),
cal.get(Calendar.YEAR),cal.get(Calendar.HOUR_OF_DAY),
cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND) );
return dateTimeStr;
} // Common.MMDDYYYY_hhmmss()
public static boolean MMDDYYYYToInts(String mmddyy,int []dF) {
String []f = mmddyy.split(SLASH);
if (f.length != 3) {
f =mmddyy.split(DASH);
if (f.length != 3) { return false; }
} //if
try {dF[0] = Stoi(f[0]);dF[1] = Stoi(f[1]);dF[2] = Stoi(f[2]);}
catch (Exception e) {return false;}
return isDateValid(dF[2],dF[0],dF[1]);
} //MMDDYYYYToInts()
public static int[] nextDay(int mm, int dd, int yyyy) {
switch(mm) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
if (dd < 31) { ++dd;}
else {
dd = 1;
if (mm == 12) {mm = 1;}
else {++mm;}
} //else it's not December
break;
case 4: case 6: case 9: case 11:
if (dd < 30) {++dd;}
else {dd = 1; ++mm;}
break;
case 2:
if (dd < 28) {dd++;}
else if (dd == 29) { dd = 1; mm = 3;}
else if (yyyy % 4 == 0 && (yyyy %100 != 0 || yyyy%400==0))
{dd++;}
else { dd = 1; mm = 3;}
break;
default:
System.out.printf("%s: %d ",
"Severe programming error, unknown month",mm);
System.exit(PROGRAM_FAILURE);
} //switch()
int [] day = {mm,dd,yyyy};
return day;
} //nextDay()
public static Calendar YYYYMMDD_hhmmssToCal(String dts) {
Calendar cal = Calendar.getInstance();
String []dateTimeTuple = dts.split(Common.BLANK);
String []dateFields = dateTimeTuple[0].split(Common.DASH);
String []timeFields = dateTimeTuple[1].split(Common.COLON);
String tStr = String.format("Common.YYYYMMDD_hhmmssToCal(): %d, %s ",
Stoi(dateFields[1]),dateFields[1]);
trace(tStr,true);
cal.set(Stoi(dateFields[0]),Stoi(dateFields[1]),
Stoi(dateFields[2]),
Stoi(timeFields[0]),Stoi(timeFields[1]),
Stoi(timeFields[2]) );
return cal;
} //YYYYMMDD_hhmmssToCal()
public static boolean isFmtYYYYMMDD_hhmmss(String dts) {
String []dateTimeTuple = dts.split(Common.BLANK);
if (dateTimeTuple.length != 2) { return false; }
String []dateFields = dateTimeTuple[0].split(Common.DASH);
if (dateFields.length != 3) { return false; }
String []timeFields = dateTimeTuple[1].split(Common.COLON);
if (timeFields.length != 3) { return false; }
for (int idx = 0; idx < dateFields.length; ++ idx) {
try { int j = Stoi(dateFields[idx]); }
catch (Exception e) { return false;}
} //for
for (int idx = 0; idx < timeFields.length; ++ idx) {
try { int j = Stoi(timeFields[idx]); }
catch (Exception e) { return false;}
} //for
return true;
} //isFmtYYYYMMDD_hhmmss()
//convert a string into an integer
static int Stoi(String s) { return Integer.parseInt(s); }
//Common.Stoi
/*
*Convert a date/time String to millis since the millenium
*/
static long dateTimeToMillis(String dateTime) {
Calendar cal = Calendar.getInstance();
String []dateTimeTuple = dateTime.split(Common.BLANK);
String []dateFields = dateTimeTuple[0].split(Common.DASH);
String []timeFields = dateTimeTuple[1].split(Common.COLON);
cal.set(Stoi(dateFields[0]),Stoi(dateFields[1]),
Stoi(dateFields[2]),
Stoi(timeFields[0]),Stoi(timeFields[1]),
Stoi(timeFields[2]) );
return calToMillis(cal);
} //dateTimeToMillis()
/*
* return milliseconds since 1/1/1970 GMT
*/
public static long calToMillis(Calendar cal) {
//cal.getTime() returns a date object, and
// the .getTime() Date instance method returns the
// milliseconds since the millenium
return cal.getTime().getTime();
} //calToMilllis
public static boolean isDateValid(int yy,int mm, int dd) {
if (yy<0 || mm < 1 || mm > 12 || dd < 1 || dd > 31) { return false;}
switch(mm) {
case 2:
if (dd <= 28) { return true; }
else if (dd >= 30) { return false; }
else if (yy % 4 == 0 && (yy %100 != 0 || yy % 400==0)){return true;}
else { return false;}
case 1: case 3: case 5: case 7: case 8: case 10: case 12:{return true;}
case 4: case 6: case 9: case 11: {
if (dd <= 30) {return true;}
else {return false; }
} //switch
} //switch() switch
return false;//keep the compiler happy
} //isDateValid()
//add days to date
public static void addDays(Calendar cal, int days) {
for (int idx = 0; idx < days; ++idx) {
cal.add(Calendar.DAY_OF_MONTH,1);
if (!isDateValid(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH) ) ) {
//Correct for months with less than 31 days
cal.set(Calendar.DAY_OF_MONTH,1);
cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) + 1);
}//if date is not valid
} //for all days to be added
} //Common.addDays()
/*
* Days it takes to double based on daily growth rate
*/
public static double daysTimes2( double growthPercent) {
return Math.log10(2)/Math.log10(1+growthPercent/100);
} //daysTimes2
} //class Common
Grouping.java :(need to be edited)
import java.util.Calendar;
import java.util.ArrayList;
import java.lang.Math;
/*
* Represents another aspect of the Johns Hopkins DB: a county like Marin,
*as opposed to a collection of counties like California
*/
public class Grouping {
String county;
String province;
String country;
double longtitude;
double latitude;
longpopulation;
//The Johns Hopkins DB has one and only one sample per date.
ArrayList
static int numGroupings;//How many Grouping objects created
// just call the ArrayList .add method()
public void add(Sample sample) { this.samples.add(sample); }
double compoundDailyGrowthRate(int first, int last, char category) {
int len = last + 1 - first;
int startVal = 0, finalVal = 0;
switch (category) {
case Common.CONFIRMED:
startVal = getSample(first).getC();
finalVal = getSample(last).getC();
break;
case Common.DECEASED:
startVal= getSample(first).getD();
finalVal= getSample(last).getD();
break;
default:
String s =
"Grouping/compoundDailyGrowthRate(): '%c' is invalid category ";
System.out.printf(s,category);
System.exit(Common.PROGRAM_FAILURE);
} //switch
if (startVal == finalVal) { return 0.0; }
double percent = Math.pow( (double)finalVal/startVal,(double)1/(len-1));
percent = (percent-1) *100;
return percent;
} // compoundDailyGrowthRate
public void clear() { this.samples.clear(); }
Grouping () {
this.county = Common.NULL_STRING;
this.longtitude = 0; this.latitude = 0;
this.population = 0;
this.samples = new ArrayList
++numGroupings;
} //Zero-arg constructor
Grouping (String cty, String p, String cntry, double lon, double lat, long pop) {
this.county = cty; this.province = p; this.country = cntry;
this.longtitude = lon; this.latitude = lat;
this.population = pop;
this.samples = new ArrayList
++numGroupings;//we've created another Grouping object
} //Grouping constructor
public long getPopulation() { return this.population; }
public int getSampleSize() { return this.samples.size(); }
public Sample getSample(int sampleNum) { return this.samples.get(sampleNum); }
public String toString() {
return Common.NULL_STRING;
} //Grouping.toString()
public static void main (String []args) {
System.out.println("*** Start Groupingclass unit test ***");
System.out.printf("Starting number of Sample objects: %d ",
Sample.numSamples);
System.out.printf("Starting number of Grouping objects: %d ",
Grouping.numGroupings);
//from 04-15-2020.csv: Napa,California,US,2020-04-15 22:56:51,
//38.50735751,-122.33283899999999,
//38,2,0,36,"Napa, California, US"
Grouping napa = new Grouping("Napa","California","US",
38.50735751,-122.33283899999999,
256000);
Calendar midApril = Calendar.getInstance();
midApril.set(2020,3,15,22,0,0);//April 15, 10 pm, 2020
long ms =Common.calToMillis(midApril); //get milliseconds since millenium
StringdateStr = Common.calToYYYYMMDD_hhmmss(midApril);
System.out.printf("Date of Napa 1st sample: %s ",dateStr);
Sample s = new Sample(38,2,0,36,ms, dateStr);
napa.add(s);
int confirmed = napa.getSample(napa.getSampleSize()-1).getC();
System.out.printf("Confirmed case count in Napa County on Apr 15: %d ",
confirmed);
midApril.set(2020,3,16,22,0,0);
ms =Common.calToMillis(midApril); //get milliseconds since millenium
dateStr = Common.calToYYYYMMDD_hhmmss(midApril);
System.out.printf("Date of Napa 2bd sample: %s ",dateStr);
s = new Sample(57,3,0,40,ms, dateStr);
napa.add(s);
double rate = napa.compoundDailyGrowthRate(0,1,Common.CONFIRMED);
System.out.printf("Growth between 1st & 2nd samples is %.3f%% ",
rate);
System.out.printf("Days to double based on growth rate %.3f ",
Common.daysTimes2(rate));
System.out.printf("Ending number of Sample objects: %d ",
Sample.numSamples);
System.out.printf("Ending number of Grouping objects: %d ",
Grouping.numGroupings);
System.out.println("*** End Grouping class unit test ***");
} //main()
} //class Grouping
Sample.java :(might or might not need to be edited)
import java.util.Calendar;
/*
* Class representing the time stamp and count in an entry in .csv file:
* ,,,,2020-04-14 23:33:31,,,9,0,0,9,"Abbeville, South Carolina, US"
*/
public class Sample {
//milliseconds since midnight January 1, 1970 GMT
long milliSecondsTimeStamp;
String textTimeStamp; //YYYY-MM-DD
int cases;
int casesD;
int casesR;
int casesA;
//tracks the number of Sample objects created
static int numSamples = 0;
public void update(int c) {this.cases += c;}
public void update(int c, int d) {this.casesD += d; this.update(c);}
public void update(int c, int d, int r) {this.casesR += r; this.update(c,d);}
public void update(int c, int d, int r, int a)
{this.casesA += a; this.update(c,d,r);}
public int getC() { return this.cases;}
public int getD() { return this.casesD;}
public int getR() { return this.casesR;}
public int getA() { return this.casesA;}
public long getMillisTS() { return this.milliSecondsTimeStamp; }
public String getTextTS() { return this.textTimeStamp; }
public String getDateStr () {
String []dateTime = this.textTimeStamp.split(Common.BLANK);
return dateTime[0];
} //getDateStr()
public Sample(int c, int d, int a, int r, long millis, String ts) {
//text time stamp is date string
this.milliSecondsTimeStamp = millis; this.textTimeStamp = ts;
this.cases = c; this.casesD = d; this.casesR = r; this.casesA = a;
numSamples++; //update the static variable to show we've created an object
} //Sampe() constructor
public static void main (String []args) {
/*
* Sample is definitely not intended as a stand alone prorgram,
*bt it is very useful to have unit test test suite.
*/
System.out.println("*** Start Sample class unit test ***");
Calendar today = Calendar.getInstance();
long ms = Common.calToMillis(today);
String todayStr = Common.calToYYYYMMDD_hhmmss(today);
Sample s = new Sample(4,1,1,3,ms,todayStr);
System.out.printf("%s Case count: %d, millis: %d ",
s.getTextTS(), s.getC(),s.getMillisTS());
System.out.printf("Ending number of samples: %d. ",
Sample.numSamples);
System.out.println("*** End Sample class unit test ***");
} //main()
} //class Sample
aggCfg.txt : (expected by CSV.java)
Terra
7530000000
Canada
37590000
US
327200000
California
39560000
Bay Area
0
baCfg.txt : (expected by CSV.java)
Alameda
1663000
Contra Costa
1147000
Marin
260955
Napa
140973
Sacramento
1531000
San Francisco
884363
San Joaquin
745424
San Mateo
727909
Santa Clara
1938000
Solano
445458
Sonoma
504217
Stanislaus
547899
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started