SlideShare a Scribd company logo
proj6/Collision.javaproj6/Collision.javapackage proj6;
import java.util.ArrayList;
/**
* Collision objects represent individual collisions occuring on
NYC streets.
* Each object contains information regarding the time, location
, number
* of injuries and fatalities and types of involved vehicles.
* @author Joanna K.
*
*/
publicclassCollisionimplementsComparable<Collision>{
staticprivateSortOrder sortOrder =SortOrder.ZIP;
privateString date;
privateString time;
privateString borough;
privateString zip;
privateint personsInjured;
privateint personsKilled;
privateint pedestriansInjured;
privateint pedestriansKilled;
privateint cyclistsInjured;
privateint cyclistsKilled;
privateint motoristsInjured;
privateint motoristsKilled;
privateString vehicleCode1;
privateString vehicleCode2;
privateString uniqueKey;
/**
* Creates a Collision object given an array of entries.
* There should be 21 string entries in the following order:
* date
* time
* borough
* zip
* lattitude^
* longitude ^
* on street name^
* cross street name ^
* personsInjured
* personsKilled
* pedestriansInjured
* pedestriansKilled
* cyclistsInjured
* cyclistsKilled
* motoristsInjured
* motoristsKilled
* contributing factor vehicle 1^
* contributing factor vehicle 2^
* uniqueKey
* vehicleCode1
* vehicleCode2
* The entries indicated with ^ are not used.
*
* @param entries an array of entries containing information
about the
* collision
* @throws IllegalArgumentException when the Collision obj
ect cannot be created
* due to errors or incompleteness of the entries parameter
*/
publicCollision(ArrayList<String> entries )throwsIllegalArgum
entException{
date = entries.get(0);
time = entries.get(1);
borough = entries.get(2);
zip = entries.get(3);
if(!verifyZip(zip)){
thrownewIllegalArgumentException("invalid zip");
}
try{
personsInjured =Integer.parseInt(entries.get(8));
personsKilled =Integer.parseInt(entries.get(9));
pedestriansInjured =Integer.parseInt(entries.get(10));
pedestriansKilled =Integer.parseInt(entries.get(11));
cyclistsInjured =Integer.parseInt(entries.get(12));
cyclistsKilled =Integer.parseInt(entries.get(13));
motoristsInjured =Integer.parseInt(entries.get(14));
motoristsKilled =Integer.parseInt(entries.get(15));
}
catch(NumberFormatException ex ){
thrownewIllegalArgumentException( ex.getMessage());
}
uniqueKey = entries.get(18);
vehicleCode1 = entries.get(19);
vehicleCode2 = entries.get(20);
}
/*
* Verifies accuracy of the zip code.
* @param zip the zip code to be verified
* @return true if zip is a valid zip code, false otherwise
*/
privateboolean verifyZip (String zip ){
if( zip.length()!=5)returnfalse;
for(int i =0; i < zip.length(); i++){
if(!Character.isDigit( zip.charAt(i))){
returnfalse;
}
}
returntrue;
}
/**
* Computes and returns string representation of this Collisio
n object.
* @see java.lang.Object#toString()
*/
@Override
publicString toString(){
return"Collision [date="+ date +", time="+ time +", borough="+
borough +", zip="+ zip
+", personsInjured="+ personsInjured +", personsKilled="+ pers
onsKilled +", pedestriansInjured="
+ pedestriansInjured +", pedestriansKilled="+ pedestriansKilled
+", cyclistsInjured="
+ cyclistsInjured +", cyclistsKilled="+ cyclistsKilled +", motori
stsInjured="+ motoristsInjured
+", motoristsKilled="+ motoristsKilled +", vehicleCode1="+ ve
hicleCode1 +", vehicleCode2="
+ vehicleCode2 +", uniqueKey="+ uniqueKey +"]";
}
/**
* Set the sort order for Collision objects to be one of the all
owed values by the SortOrder enumerator.
* @param sortOrder the sortOrder to set
*/
publicstaticvoid setSortOrder(SortOrder sortOrder){
Collision.sortOrder = sortOrder;
}
/**
* Compares two Collision objects based on their zip code, n
umber of cyclist-injuries or
* number of person-
injuries. The comparison is determined by the value of a flag set
by
* setSortOrder() method.
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@Override
publicint compareTo(Collision other){
if( sortOrder ==SortOrder.ZIP ){
returnthis.zip.compareTo(other.zip);
}
elseif(sortOrder ==SortOrder.CYCLISTS){
return((this.cyclistsInjured +this.cyclistsKilled)
-(other.cyclistsInjured +this.cyclistsKilled ));
}
elseif(sortOrder ==SortOrder.PERSONS){
return((this.personsInjured +this.personsKilled)
-(other.personsInjured +this.personsKilled ));
}
return0;
}
/**
* Return the time of this Collision object.
* @return the time
*/
publicString getTime(){
return time;
}
/**
* Return the zip code of this Collision object.
* @return the zip
*/
publicString getZip(){
return zip;
}
/**
* Return the number of injured cyclists of this Collision obje
ct.
* @return the cyclistsInjured
*/
publicint getCyclistsInjured(){
return cyclistsInjured;
}
/**
* Return the number of killed cyclists of this Collision objec
t.
* @return the cyclistsKilled
*/
publicint getCyclistsKilled(){
return cyclistsKilled;
}
/**
* Return the number of injured persons of this Collision obje
ct.
* @return the personsInjured
*/
publicint getPersonsInjured(){
return personsInjured;
}
/**
* Return the number of killed persons of this Collision objec
t.
* @return the personsKilled
*/
publicint getPersonsKilled(){
return personsKilled;
}
/**
* Return the number of injured pedestrians of this Collision
object.
* @return the pedestriansInjured
*/
publicint getPedestriansInjured(){
return pedestriansInjured;
}
/**
* Return the number of killed pedestrians of this Collision o
bject.
* @return the pedestriansKilled
*/
publicint getPedestriansKilled(){
return pedestriansKilled;
}
/**
* Return the number of injured motorists of this Collision ob
ject.
* @return the motoristsInjured
*/
publicint getMotoristsInjured(){
return motoristsInjured;
}
/**
* Return the number of killed motorists of this Collision obj
ect.
* @return the motoristsKilled
*/
publicint getMotoristsKilled(){
return motoristsKilled;
}
/**
* Return the vehicle 1 of this Collision object.
* @return the vehicleCode1
*/
publicString getVehicleCode1(){
return vehicleCode1;
}
/**
* Return the vehicle 2 of this Collision object.
* @return the vehicleCode2
*/
publicString getVehicleCode2(){
return vehicleCode2;
}
}
proj6/CollisionInfo.javaproj6/CollisionInfo.java
package proj6;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
/**
* This is a program that computes some information about the d
ata posted by
* OpenNYC regarding the collision records on the streets of N
YC.
*
* @author Joanna K.
*
*/
publicclassCollisionInfo{
/**
* The main method that starts the program. It is responsible
for opening and reading the
* input file, creating the CollisionList object and using it co
mpute the
* predetermined results.
* @param args the array should contain the name of the inpu
t file as the first element,
* all other elements are ignored
* @throws FileNotFoundException if the input file is corrup
ted or vanishes during the
* execution of this program
*/
publicstaticvoid main(String[] args)throwsFileNotFoundExcepti
on{
finalint NUM_OF_ENTRIES =21;
long startTimer, elapsedTime1, elapsedTime2;
startTimer =System.nanoTime();
if(args.length <1){
System.err.println("File name missing");
System.exit(0);
}
File fileName =newFile(args[0]);
if(!fileName.canRead()){
System.err.printf("Cannot read from file %sn.", fileName.getA
bsolutePath());
System.exit(0);
}
Scanner fin =newScanner(fileName);
CollisionList list =newCollisionList();
while( fin.hasNextLine()){
String textLine = fin.nextLine();
ArrayList<String> words = split (textLine );
if(words.size()!= NUM_OF_ENTRIES){
continue;//skip lines that are not complete
}
list.add(words);
}
elapsedTime1 =System.nanoTime()- startTimer;
startTimer =System.nanoTime();
//task 1
System.out.println("ZIP codes with the largest number of collisi
ons:");
System.out.println( list.getZipCodesWithMostCollisions(3));
//task2
System.out.println("ZIP codes with the fewest number of collisi
ons:");
System.out.println( list.getZipCodesWithLeastCollisions(3));
//task 3
System.out.println("ZIP codes with the most injuries and fataliti
es (combined):");
System.out.println( list.getZipCodesWithMostPersonIncidents(3
));
//task 4
System.out.println("ZIP codes with the most cyclist injuries and
fatalities:");
System.out.println( list.getZipCodesWithMostCyclistIncidents(3
));
//task5:
System.out.println("Percentage of collisions involving certain v
ehicle type:");
System.out.println(list.getVehicleTypeStats());
//task6:
System.out.println("Fraction of collisions by hour:");
System.out.println(list.getHourlyStats());
elapsedTime2 =System.nanoTime()- startTimer;
System.out.println("nn=============================
===============n");
System.out.printf("Reading and storing data: %,15d nanosecond
sn", elapsedTime1);
System.out.printf("Computation of results : %,15d nanoseconds
n", elapsedTime2);
fin.close();
}
/**
* Splits a given line according to commas (commas within e
ntries are ignored)
* @param textLine line of text to be parsed
* @return an ArrayList object containing all individual entri
es/tokens
* found on the line.
*/
publicstaticArrayList<String> split (String textLine ){
ArrayList<String> entries =newArrayList<String>();
int lineLength = textLine.length();
StringBuffer nextWord =newStringBuffer();
char nextChar;
boolean insideQuotes =false;
for(int i =0; i < lineLength; i++){
nextChar = textLine.charAt(i);
//add character to the current entry
if( nextChar !=','&& nextChar !='"'){
nextWord.append( nextChar );
}
//double quote found, decide if it is opening or closing one
elseif(nextChar =='"'){
if( insideQuotes ){
insideQuotes =false;
}
else{
insideQuotes =true;
}
}
//found comma inside double quotes, just add it to the string
elseif(nextChar ==','&& insideQuotes){
nextWord.append( nextChar );
}
//end of the current entry reached, add it to the list of entries
//and reset the nextWord to empty string
elseif(nextChar ==','&&!insideQuotes){
//trim the white space before adding to the list
entries.add( nextWord.toString().trim());
nextWord =newStringBuffer();
}
else{
System.err.println("This should never be printed.n");
}
}
//add the last word
//trim the white space before adding to the list
entries.add( nextWord.toString().trim());
return entries;
}
}
proj6/CollisionList.javaproj6/CollisionList.javapackage proj6;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/**
* CollisionList class stores a list of collisions. The organizatio
n of this list is
* based on the zip code associated with a given collision. This
organization simplifies
* processing of collisions that occur within a particular zip cod
e.
* @author Joanna K.
*/
publicclassCollisionList{
privateArrayList<ZipCodeList> list;
/**
* Creates an empty CollisionList object.
*/
publicCollisionList(){
list =newArrayList<ZipCodeList>();
}
/**
* Adds a particular record to this CollisionList object.
* The record should consist of 21 string entries in the follow
ing order:
* date
* time
* borough
* zip
* lattitude^
* longitude ^
* on street name^
* cross street name ^
* personsInjured
* personsKilled
* pedestriansInjured
* pedestriansKilled
* cyclistsInjured
* cyclistsKilled
* motoristsInjured
* motoristsKilled
* contributing factor vehicle 1^
* contributing factor vehicle 2^
* uniqueKey
* vehicleCode1
* vehicleCode2
* The entries indicated with ^ are not used.
*
* @param record an list of string describing a particular coll
ision (see above
* for order of entries)
* @return true if the record was added to this CollisionList
object, false if any
* problem occurred and the record was not added
*/
publicboolean add (ArrayList<String> record ){
try{
Collision col =newCollision(record);
ZipCodeList tmp =newZipCodeList(col);
int index = list.indexOf(tmp);
if(index >=0){//add the collision object to the existing zip code
list
list.get(index).add(col);
}
else{//add the new zip code list
list.add(tmp);
}
}
catch(IllegalArgumentException ex ){
returnfalse;//return false if the Collision constructor failed
}
returntrue;//return true to indicate that the object was added
}
/**
* Determines k zip codes with most collisions in this Collisi
onList object.
* @param k number of zip codes with the highest number of
collisions
* @return a string formatted as
* zip numOfCollisions
* one per line, that contains k zip codes with the highest nu
mber of collisions
*/
publicString getZipCodesWithMostCollisions (int k){
@SuppressWarnings("unchecked")
ArrayList<ZipCodeList> sortedList =(ArrayList<ZipCodeList>)
list.clone();
//sort the list
Collections.sort(sortedList,newCompareByNumOfCollisionsDes
cending());
StringBuffer result =newStringBuffer();
int count =0;
for(int i =0; i < k && i < sortedList.size()&& count<sortedList.
size(); i++){
do{
result.append(String.format(" %5s %5d collisions
n",sortedList.get(count).getZip(),
sortedList.get(count).getTotalNumOfCollisions()))
;
count++;
}while( count+1< sortedList.size()
&& sortedList.get(count).getTotalNumOfCollisions()
== sortedList.get(count+1).getTotalNumOfCollisions());
}
return result.toString();
}
/**
* Determines k zip codes with least collisions in this Collisi
onList object.
* @param k number of zip codes with the lowest number of
collisions
* @return a string formatted as
* zip numOfCollisions
* one per line, that contains k zip codes with the lowest nu
mber of collisions
*/
publicString getZipCodesWithLeastCollisions (int k){
@SuppressWarnings("unchecked")
ArrayList<ZipCodeList> sortedList =(ArrayList<ZipCodeList>)
list.clone();
//sort the list
Collections.sort(sortedList,newCompareByNumOfCollisionsAsc
ending());
StringBuffer result =newStringBuffer();
int count =0;
for(int i =0; i < k && i < sortedList.size()&& count<sortedList.
size(); i++){
do{
result.insert(0,String.format(" %5s %5d collisions
n",sortedList.get(count).getZip(),
sortedList.get(count).getTotalNumOfCollisions()))
;
count++;
}while( count+1< sortedList.size()
&& sortedList.get(count).getTotalNumOfCollisions()
== sortedList.get(count+1).getTotalNumOfCollisions());
}
return result.toString();
}
/**
* Determines k zip codes with most number of collisions inv
olving
* cyclists in this CollisionList object.
* @param k number of zip codes with the highest number of
collisions that involved cyclists
* @return a string formatted as
* zip numOfCycliststHurt (numOfCyclists killed)
* one per line, that contains k zip codes with the highest nu
mber of injured cyclists
*/
publicString getZipCodesWithMostCyclistIncidents (int k ){
@SuppressWarnings("unchecked")
ArrayList<ZipCodeList> sortedList =(ArrayList<ZipCodeList>)
list.clone();
//sort the list
CompareByNumOfCyclistsIncidentsDescending comp =newCom
pareByNumOfCyclistsIncidentsDescending();
Collections.sort(sortedList, comp );
StringBuffer result =newStringBuffer();
int inj =0, killed =0;
int count =0;
for(int i =0; i < k && i < sortedList.size()&& count< sortedList.
size(); i++){
do{
inj = sortedList.get(count).getTotalNumOfCyclistsInj
ured();
killed = sortedList.get(count).getTotalNumOfCyclist
sKilled();
result.append(String.format(" %5s %5d (%3d kille
d ) cyclists hurtn", sortedList.get(count).getZip(),
inj + killed, killed ));
count++;
}
while( count+1< sortedList.size()
&&0== comp.compare(sortedList.get(count), sortedList.get(cou
nt+1)));
}
return result.toString();
}
/**
* Determines k zip codes with most number of injured and ki
lled persons.
* @param k number of zip codes with the highest number of
injured and killed persons
* @return a string formatted as
* zip numOfPersonsHurt (numOfPersons killed)
* one per line, that contains k zip codes with the highest nu
mber of injured persons
*/
publicString getZipCodesWithMostPersonIncidents (int k ){
@SuppressWarnings("unchecked")
ArrayList<ZipCodeList> sortedList =(ArrayList<ZipCodeList>)
list.clone();
//sort the list
CompareByNumOfPersonsIncidentsDescending comp =newCom
pareByNumOfPersonsIncidentsDescending();
Collections.sort(sortedList, comp );
StringBuffer result =newStringBuffer();
int inj =0, killed =0;
int count =0;
for(int i =0; i < k && i < sortedList.size()&& count< sortedList.
size(); i++){
do{
inj = sortedList.get(count).getTotalNumOfPersonsInj
ured();
killed = sortedList.get(count).getTotalNumOfPerson
sKilled();
result.append(String.format(" %5s %5d (%3d kille
d ) persons hurtn", sortedList.get(count).getZip(),
inj + killed, killed ));
count++;
}
while( count+1< sortedList.size()
&&0== comp.compare(sortedList.get(count), sortedList.get(cou
nt+1)));
}
return result.toString();
}
/**
* Computes percentage of total collisions in this CollisionLi
st object that involved one
* of the following vehicle types: taxi, bus, bicycle, truck, fir
e truck and ambulance.
* @return a string containing the results of the computation
*/
publicString getVehicleTypeStats (){
String result =newString();
int taxi =0;
int bus =0;
int bicycle =0;
int fireTruck =0;
int ambulance =0;
int totalNumOfCollisions =0;
for(ZipCodeList l : list ){
totalNumOfCollisions += l.getTotalNumOfCollisions();
for(Collision c : l ){
if(c.getVehicleCode1().equalsIgnoreCase("taxi")||
c.getVehicleCode2().equalsIgnoreCase("taxi"))
taxi++;
if(c.getVehicleCode1().equalsIgnoreCase("bus")||
c.getVehicleCode2().equalsIgnoreCase("bus"))
bus++;
if(c.getVehicleCode1().equalsIgnoreCase("bicycle")||
c.getVehicleCode2().equalsIgnoreCase("bicycle
")) bicycle++;
if(c.getVehicleCode1().equalsIgnoreCase("fire truck")||
c.getVehicleCode2().equalsIgnoreCase("fire tru
ck")) fireTruck++;
if(c.getVehicleCode1().equalsIgnoreCase("ambulance")||
c.getVehicleCode2().equalsIgnoreCase("ambula
nce")) ambulance++;
}
}
//create a string object with results
result +=String.format(" %-
11s %5.2f%%n","taxi",(float)(taxi)/totalNumOfCollisions*100)
;
result +=String.format(" %-
11s %5.2f%%n","bus",(float)(bus)/totalNumOfCollisions*100);
result +=String.format(" %-
11s %5.2f%%n","bicycle",(float)(bicycle)/totalNumOfCollision
s*100);
result +=String.format(" %-
11s %5.2f%%n","fire truck",(float)(fireTruck)/totalNumOfColl
isions*100);
result +=String.format(" %-
11s %5.2f%%n","ambulance",(float)(ambulance)/totalNumOfC
ollisions*100);
return result;
}
/**
* Computes percentage of total collisions in this CollisionLi
st object that occured within
* a particular hour. The collisions are placed into bins of 1 h
our intervals.
* @return a string containing the results of the computation
*/
publicString getHourlyStats (){
StringBuffer result =newStringBuffer();
//counter for each hour
int[] hourlyCount =newint[24];
String hour ="", time ="";
StringBuffer bar;
int totalNumOfCollisions =0;
for(ZipCodeList l : list ){
totalNumOfCollisions += l.getTotalNumOfCollisions();
for(Collision c : l ){
try{
//extract the hour from the time entry
time = c.getTime();
hour = time.substring(0,time.indexOf(':')).trim();
//increment counter for that hour
hourlyCount[Integer.parseInt(hour)]++;
}catch(IndexOutOfBoundsException e){
//ignore incorrectly formed times
}catch(NumberFormatException e ){
//ignore incorrectly formed times
}
}
}
for(int i =0; i <24; i++){
//determine number of "bars" to be printed for visual representat
ion of
//the histogram
int numOfBars =(int)(((double)hourlyCount[i]/totalNumOfColli
sions)*240);
bar =newStringBuffer(numOfBars);
for(int j =0; j < numOfBars; j++)
bar.append("|");
result.append(String.format("%3d h %5.1f%% %s%n",
i,100.0*hourlyCount[i]/totalNumOfCollisions, bar.
toString()));
}
return result.toString();
}
}
/*
* Comparator class for comparing two @see ZipCodeList objec
ts based on the
* number of collisions occurring in each. The resulting order is
ascending.
* @author Joanna K.
*
*/
classCompareByNumOfCollisionsAscendingimplementsCompar
ator<ZipCodeList>{
/* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java
.lang.Object)
*/
@Override
publicint compare(ZipCodeList arg0,ZipCodeList arg1){
return arg0.getTotalNumOfCollisions()-
arg1.getTotalNumOfCollisions();
}
}
/*
* Comparator class for comparing two @see ZipCodeList objec
ts based on the
* number of collisions occurring in each. The resulting order is
descending.
* @author Joanna K.
*
*/
classCompareByNumOfCollisionsDescendingimplementsCompa
rator<ZipCodeList>{
/* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java
.lang.Object)
*/
@Override
publicint compare(ZipCodeList arg0,ZipCodeList arg1){
return arg1.getTotalNumOfCollisions()-
arg0.getTotalNumOfCollisions();
}
}
/*
* Comparator class for comparing two @see ZipCodeList objec
ts based on the
* number of injured persons. The resulting order is descending.
Ties are resolved
* based on the number of killed persons.
* @author Joanna K.
*
*/
classCompareByNumOfPersonsIncidentsDescendingimplements
Comparator<ZipCodeList>{
@Override
publicint compare(ZipCodeList arg0,ZipCodeList arg1){
int diff =( arg1.getTotalNumOfPersonsInjured()+ arg1.getTotal
NumOfPersonsKilled())
-
( arg0.getTotalNumOfPersonsInjured()+ arg0.getTotalNumOfPe
rsonsKilled());
if(diff !=0)
return diff;
elsereturn( arg1.getTotalNumOfPersonsKilled()-
arg0.getTotalNumOfPersonsKilled());
}
}
/*
* Comparator class for comparing two @see ZipCodeList objec
ts based on the
* number of injured persons. The resulting order is ascending.
Ties are resolved
* based on the number of killed persons.
* @author Joanna K.
*
*/
classCompareByNumOfPersonsIncidentsAscendingimplementsC
omparator<ZipCodeList>{
@Override
publicint compare(ZipCodeList arg0,ZipCodeList arg1){
int diff =-
( arg1.getTotalNumOfPersonsInjured()+ arg1.getTotalNumOfPe
rsonsKilled())
+( arg0.getTotalNumOfPersonsInjured()+ arg0.getTotalNumOfP
ersonsKilled());
if(diff !=0)
return diff;
elsereturn(-
arg1.getTotalNumOfPersonsKilled()+ arg0.getTotalNumOfPerso
nsKilled());
}
}
/*
* Comparator class for comparing two @see ZipCodeList objec
ts based on the
* number of injured cyclists. The resulting order is descending.
Ties are resolved
* based on the number of killed cyclists.
* @author Joanna K.
*
*/
classCompareByNumOfCyclistsIncidentsDescendingimplements
Comparator<ZipCodeList>{
@Override
publicint compare(ZipCodeList arg0,ZipCodeList arg1){
int diff =( arg1.getTotalNumOfCyclistsInjured()+ arg1.getTotal
NumOfCyclistsKilled())
-
( arg0.getTotalNumOfCyclistsInjured()+ arg0.getTotalNumOfC
yclistsKilled());
if(diff !=0)
return diff;
elsereturn( arg1.getTotalNumOfCyclistsKilled()-
arg0.getTotalNumOfCyclistsKilled());
}
}
/*
* Comparator class for comparing two @see ZipCodeList objec
ts based on the
* number of injured cyclists. The resulting order is ascending.
Ties are resolved
* based on the number of killed cyclists.
* @author Joanna K.
*
*/
classCompareByNumOfCyclistsIncidentsAscendingimplementsC
omparator<ZipCodeList>{
@Override
publicint compare(ZipCodeList arg0,ZipCodeList arg1){
int diff =-
( arg1.getTotalNumOfCyclistsInjured()+ arg1.getTotalNumOfC
yclistsKilled())
+( arg0.getTotalNumOfCyclistsInjured()+ arg0.getTotalNumOf
CyclistsKilled());
if(diff !=0)
return diff;
elsereturn(-
arg1.getTotalNumOfCyclistsKilled()+ arg0.getTotalNumOfCycl
istsKilled());
}
}
proj6/SortOrder.javaproj6/SortOrder.javapackage proj6;
/**
* Enumerator used to decide on sort order of Collision objects.
* @author Joanna K.
*
*/
enum SortOrder{ ZIP, CYCLISTS, PERSONS}
proj6/ZipCodeList.javaproj6/ZipCodeList.javapackage proj6;
import java.util.ArrayList;
import java.util.Iterator;
/**
* ZipCodeList contains collision objects that all occured in the
same zip
* code. It keeps track of additional information like total numb
er of
* collisions, injuries and fatalities.
* @author Joanna K.
*
*/
publicclassZipCodeListimplementsIterable<Collision>,Compara
ble<ZipCodeList>{
privateArrayList<Collision> list;
privateString zip;
privateint totalNumOfCollisions;
privateint totalNumOfPersonsInjured;
privateint totalNumOfPersonsKilled;
privateint totalNumOfCyclistsInjured;
privateint totalNumOfCyclistsKilled;
privateint totalNumOfPedestriansInjured;
privateint totalNumOfPedestriansKilled;
privateint totalNumOfMotoristsInjured;
privateint totalNumOfMotoristsKilled;
/**
* Creates a ZipCodeList objects based on the first collision.
The
* zip code for this ZipCodeList is set to the zip code
* associated with the collision col.
* @param col the initial collisions for this ZipCodeList obje
ct
*/
publicZipCodeList(Collision col ){
list =newArrayList<Collision>();
zip = col.getZip();
add(col);
}
/**
* Adds another Collision object to this ZipCodeList object.
* @param col a Collision object to be added to this ZipCode
List object
* @throws IllegalArgumentException when the zip code of t
he new Collision
* object col is not the same as the zip code for this ZipCode
List object
*/
publicvoid add (Collision col)throwsIllegalArgumentException{
if(col ==null)return;
if(!col.getZip().equals(zip))
thrownewIllegalArgumentException("Error: zip codes are not m
atching. ");
list.add(col);
totalNumOfCollisions ++;
totalNumOfPersonsInjured += col.getPersonsInjured();
totalNumOfPersonsKilled += col.getPersonsKilled();
totalNumOfCyclistsInjured += col.getCyclistsInjured();
totalNumOfCyclistsKilled += col.getCyclistsKilled();
totalNumOfPedestriansInjured += col.getPedestriansInjure
d();
totalNumOfPedestriansKilled += col.getPedestriansKilled(
);
totalNumOfMotoristsInjured += col.getMotoristsInjured();
totalNumOfMotoristsKilled += col.getMotoristsKilled();
}
/**
* Returns an iterator for this ZipCodeList object.
* @see java.lang.Iterable#iterator()
*/
@Override
publicIterator<Collision> iterator(){
return list.iterator();
}
/**
* Computes the hash code for this ZipCodeList object. The h
ashcode
* is based on the zip code associated with this object.
* @see java.lang.Object#hashCode()
*/
@Override
publicint hashCode(){
finalint prime =31;
int result =1;
result = prime * result +((zip ==null)?0: zip.hashCode());
return result;
}
/**
* Returns true if this ZipCodeList object and the parameter h
ave the
* same zip code associated with them. Returns false otherwis
e.
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
publicboolean equals(Object obj){
if(this== obj)
returntrue;
if(obj ==null)
returnfalse;
if(getClass()!= obj.getClass())
returnfalse;
ZipCodeList other =(ZipCodeList) obj;
if(zip ==null){
if(other.zip !=null)
returnfalse;
}elseif(!zip.equals(other.zip))
returnfalse;
returntrue;
}
/**
* Compares two ZioCodeList objects based on the zip code v
alue stored in them.
* The results are based on string comparison of the two zip c
odes.
* @see java.lang.Comparable#compareTo(java.lang.Object)
* Compares two ZipCodeList objects based on the zip codes.
*/
@Override
publicint compareTo(ZipCodeList o){
return zip.compareTo(o.zip);
}
/**
* Returns the zip code of this ZipCodeList object
* @return the zip
*/
publicString getZip(){
return zip;
}
/**
* Returns the total number of collisions of this ZipCodeList
object
* @return the totalNumOfCollisions
*/
publicint getTotalNumOfCollisions(){
return totalNumOfCollisions;
}
/**
* Returns the total number of persons injured of this ZipCo
deList object
* @return the totalNumOfPersonsInjured
*/
publicint getTotalNumOfPersonsInjured(){
return totalNumOfPersonsInjured;
}
/**
* Returns the total number of persons killed of this ZipCode
List object
* @return the totalNumOfPersonsKilled
*/
publicint getTotalNumOfPersonsKilled(){
return totalNumOfPersonsKilled;
}
/**
* Returns the total number of cyclists injured of this ZipCo
deList object
* @return the totalNumOfCyclistsInjured
*/
publicint getTotalNumOfCyclistsInjured(){
return totalNumOfCyclistsInjured;
}
/**
* Returns the total number of cyclists killed of this ZipCode
List object
* @return the totalNumOfCyclistsKilled
*/
publicint getTotalNumOfCyclistsKilled(){
return totalNumOfCyclistsKilled;
}
/**
* Returns the total number of pedestrians injured of this Zip
CodeList object
* @return the totalNumOfPedestriansInjured
*/
publicint getTotalNumOfPedestriansInjured(){
return totalNumOfPedestriansInjured;
}
/**
* Returns the total number of pedestrians killed of this ZipC
odeList object
* @return the totalNumOfPedestriansKilled
*/
publicint getTotalNumOfPedestriansKilled(){
return totalNumOfPedestriansKilled;
}
/**
* Returns the total number of motorists injured of this ZipC
odeList object
* @return the totalNumOfMotoristsInjured
*/
publicint getTotalNumOfMotoristsInjured(){
return totalNumOfMotoristsInjured;
}
/**
* Returns the total number of motorists killed of this ZipCo
deList object
* @return the totalNumOfMotoristsKilled
*/
publicint getTotalNumOfMotoristsKilled(){
return totalNumOfMotoristsKilled;
}
/**
* Computes and returns a string representation of this ZipCo
deList object.
* @see java.lang.Object#toString()
*/
@Override
publicString toString(){
return"ZipCodeList for "+ zip +": "+ totalNumOfCollisions +",
"+ totalNumOfPersonsInjured +", "
+ totalNumOfPersonsKilled +", "+ totalNumOfCyclistsInjured +
", "+ totalNumOfCyclistsKilled +", "
+ totalNumOfPedestriansInjured +", "+ totalNumOfPedestrians
Killed +", "+ totalNumOfMotoristsInjured
+", "+ totalNumOfMotoristsKilled ;
}
}
CSCI-UA 102 sec 3,5, Fall 2015
Programming Project 6
Joanna Klukowska
[email protected]
Programming Project 6:
NYPD Motor Vehicle Collisions Analysis - Revisited
Due date: Dec. 11, 11:55 PM EST.
You may discuss any of the assignments with your classmates
and tutors (or anyone else) but all work for all assignments must
be entirely your own. Any sharing or copying of assignments
will be considered cheating. If you get significant help from
anyone,
you should acknowledge it in your submission (and your grade
will be proportional to the part that you completed on your
own).
You are responsible for every line in your program: you need to
know what it does and why. You should not use any data
structures or features of Java that have not been covered in class
(or the prerequisite class). If you have doubts whether or not
you are allowed to use certain structures, just ask your
instructor.
In this project you will revisit your project 1 implementation of
a program that used the NYPD motor vehicle collision data. A
version
of the solution to the original project is provided (it has been
slightly modified from the specification of the original project).
You should
use that implementation as the basis for your project 6 solution.
Please, see project 1 for the details of tasks and implementation
requirements.
Objectives
The goal of this programming project is for you to master (or at
least get practice on) the following tasks:
• using/modifying existing code
• selecting data structures appropriate for given tasks
• writing Java programs
The Program Input and Output
You should not change this part of the implementation.
There are three data sets posted on the course website that you
should be using for this project. The largest of them contains all
collision
data for the entire NYC from July 1, 2012 till June 30, 2015
(three years total). The medium size data set contains all
collision data for
the entire NYC from July 1, 2013 till June 30, 2015 (two years
total). Finally, the smallest data set contains all collision data
for the
entire NYC from July 1, 2014 till June 30, 2015 (one year
total).
For testing purposes, you may wish to use smaller data sets.
Computational Task
The posted program stores all the Collision objects in an
ArrayList of ZipCodeList objects. The ZipCodeList object, in
turn, stores all Collision objects from a particular zip code in an
ArrayList of collisions.
At this point in the semester, you should realize that this is not
an optimal way of organizing the data. Your task for this project
is to
modify how the Collision objects are stored in memory when
the program is running in order to improve the time
performance of the
program.
1
CSCI-UA 102 sec 3,5, Fall 2015
Programming Project 6
Joanna Klukowska
[email protected]
You do not need to provide implementation of any data
structures yourself. You should use the implementations
provided by Java API.
You should only use the data structures that we discussed in
class during this semester. Here is the list with links to Java
API interfaces
and classes:
• linked list
https://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.ht
ml
• stack
https://docs.oracle.com/javase/8/docs/api/java/util/Stack.html
• queue
https://docs.oracle.com/javase/8/docs/api/java/util/Queue.html
(any of the implementing classes)
• (self-balancing) binary search tree
http://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html
• priority queue
https://docs.oracle.com/javase/8/docs/api/java/util/PriorityQueu
e.html
• hashtable
https://docs.oracle.com/javase/8/docs/api/java/util/Map.html
(any of the implementing classes)
You are not supposed to use all of the above data structures.
Your task is to decide which of them could improve the time
performance
of the program and use those.
You may wish to try several different changes. In your final
program you should leave only the changes that resulted in a
better time
performance of the program. All other changes should be
described in the written report (see below).
Written Report: Performance Analysis
You should write a 1-2 page report that summarizes the results
of this project. Your report should include justification for why
particular
data structures are appropriate and others are not. You may wish
to include time comparison results for different sizes of data
sets that
you obtain with the provided version of the code and with your
modified version of the code. If you tried some of the data
structures and
they did not turn out to be appropriate, mention that in your
report.
If you decide to include graphs and tables, those do not count
towards the 2-page limit.
Program Design
You should only change parts of the design of this program that
are related to change in data structures. Overall program design
should
remain the same.
Programming Rules
You should follow the rules outlined in the document Code
conventions posted on the course website at http://cs.nyu.edu/
˜joannakl/cs102_f15/notes/CodeConventions.pdf.
You must document all your code using Javadoc. Your class
documentation needs to provide a description of what it is used
for and
the name of its author. Your methods need to have description,
specification of parameters, return values, exceptions thrown
and any
assumptions that they are making.
A class’s data fields and methods should not be declared static
unless they are to be shared by all instances of the class or
provide
access to such data.
You must use the provided implementation of the program and
modify only the parts that change the storage of Collision
objects.
Grading
Make sure that you are following all the rules in the
Programming Rules section above.
If your program does not compile or crashes (almost) every time
it is ran, you will get a zero on the assignment.
2
https://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.ht
ml
https://docs.oracle.com/javase/8/docs/api/java/util/Stack.html
https://docs.oracle.com/javase/8/docs/api/java/util/Queue.html
http://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html
https://docs.oracle.com/javase/8/docs/api/java/util/PriorityQueu
e.html
https://docs.oracle.com/javase/8/docs/api/java/util/Map.html
http://cs.nyu.edu/~joannakl/cs102_f15/notes/CodeConventions.p
df
http://cs.nyu.edu/~joannakl/cs102_f15/notes/CodeConventions.p
df
CSCI-UA 102 sec 3,5, Fall 2015
Programming Project 6
Joanna Klukowska
[email protected]
If the program does not adhere to the specification, the grade
will be low and will depend on how easy it is to figure out what
the program
is doing.
30 points choice and use of data structures,
40 points written report with analysis of the observations,
10 points use of existing program structure,
20 points proper documentation and program style (for the parts
of the code that you modify; you should add your name as the
author
for the classes that you modify).
How and What to Submit
Your should submit all your source code files (the ones with
.java extensions only) and your report (in PDF format) in a
single zip file to
NYU Classes. If you are unsure how to create a zip file or how
to get to your source code files, you should ask long before the
project is
due.
If you wish to use your (one and only) freebie for this project
(one week extension, no questions asked), then complete the
form at
http://goo.gl/forms/YFDVBlscEB before the due date for the
assignment. All freebies are due seven days after the original
due date and should be submitted to NYU Classes.
3
http://goo.gl/forms/YFDVBlscEB

More Related Content

Similar to proj6Collision.javaproj6Collision.javapackage proj6;import.docx

package reservation; import java.util.; For Scanner Class .pdf
 package reservation; import java.util.; For Scanner Class .pdf package reservation; import java.util.; For Scanner Class .pdf
package reservation; import java.util.; For Scanner Class .pdf
anitasahani11
 
#include iostream #include string#includeiomanip using.docx
#include iostream #include string#includeiomanip using.docx#include iostream #include string#includeiomanip using.docx
#include iostream #include string#includeiomanip using.docx
ajoy21
 
cpp_sample
cpp_samplecpp_sample
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기
Arawn Park
 
import java-util--- import java-io--- class Vertex { -- Constructo.docx
import java-util--- import java-io---   class Vertex {   -- Constructo.docximport java-util--- import java-io---   class Vertex {   -- Constructo.docx
import java-util--- import java-io--- class Vertex { -- Constructo.docx
Blake0FxCampbelld
 
Create a system to simulate vehicles at an intersection. Assume th.pdf
Create a system to simulate vehicles at an intersection. Assume th.pdfCreate a system to simulate vehicles at an intersection. Assume th.pdf
Create a system to simulate vehicles at an intersection. Assume th.pdf
archanacomputers1
 
Java serialization
Java serializationJava serialization
PersonData.h#ifndef PersonData_h #define PersonData_h#inclu.pdf
 PersonData.h#ifndef PersonData_h #define PersonData_h#inclu.pdf PersonData.h#ifndef PersonData_h #define PersonData_h#inclu.pdf
PersonData.h#ifndef PersonData_h #define PersonData_h#inclu.pdf
annamalaiagencies
 
C#i need help creating the instance of stream reader to read from .pdf
C#i need help creating the instance of stream reader to read from .pdfC#i need help creating the instance of stream reader to read from .pdf
C#i need help creating the instance of stream reader to read from .pdf
ajantha11
 
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Codemotion
 
Please do Part A, Ill be really gratefulThe main.c is the skeleto.pdf
Please do Part A, Ill be really gratefulThe main.c is the skeleto.pdfPlease do Part A, Ill be really gratefulThe main.c is the skeleto.pdf
Please do Part A, Ill be really gratefulThe main.c is the skeleto.pdf
aioils
 
Complete skeletonimport java.util.ArrayList; public class My.pdf
Complete skeletonimport java.util.ArrayList; public class My.pdfComplete skeletonimport java.util.ArrayList; public class My.pdf
Complete skeletonimport java.util.ArrayList; public class My.pdf
arhamnighty
 
Production.javapublic class Production {    Declaring instance.pdf
Production.javapublic class Production {    Declaring instance.pdfProduction.javapublic class Production {    Declaring instance.pdf
Production.javapublic class Production {    Declaring instance.pdf
sooryasalini
 
Game unleashedjavascript
Game unleashedjavascriptGame unleashedjavascript
Game unleashedjavascript
Reece Carlson
 
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx
Adamq0DJonese
 
infoShare 2014: Gino Marckx, Forget about Agile, let's write great code first!
infoShare 2014: Gino Marckx, Forget about Agile, let's write great code first!infoShare 2014: Gino Marckx, Forget about Agile, let's write great code first!
infoShare 2014: Gino Marckx, Forget about Agile, let's write great code first!
Infoshare
 
C346_PA3_W12srccommonBaseThread.javaC346_PA3_W12srccommonB.docx
C346_PA3_W12srccommonBaseThread.javaC346_PA3_W12srccommonB.docxC346_PA3_W12srccommonBaseThread.javaC346_PA3_W12srccommonB.docx
C346_PA3_W12srccommonBaseThread.javaC346_PA3_W12srccommonB.docx
humphrieskalyn
 
assignmentTwoCar.javaassignmentTwoCar.javapackage assignmentTw.docx
assignmentTwoCar.javaassignmentTwoCar.javapackage assignmentTw.docxassignmentTwoCar.javaassignmentTwoCar.javapackage assignmentTw.docx
assignmentTwoCar.javaassignmentTwoCar.javapackage assignmentTw.docx
ssuser562afc1
 
Modify the bouncing ball example demonstrated/tutorialoutlet
Modify the bouncing ball example demonstrated/tutorialoutletModify the bouncing ball example demonstrated/tutorialoutlet
Modify the bouncing ball example demonstrated/tutorialoutlet
Cleasbyz
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.
Russell Childs
 

Similar to proj6Collision.javaproj6Collision.javapackage proj6;import.docx (20)

package reservation; import java.util.; For Scanner Class .pdf
 package reservation; import java.util.; For Scanner Class .pdf package reservation; import java.util.; For Scanner Class .pdf
package reservation; import java.util.; For Scanner Class .pdf
 
#include iostream #include string#includeiomanip using.docx
#include iostream #include string#includeiomanip using.docx#include iostream #include string#includeiomanip using.docx
#include iostream #include string#includeiomanip using.docx
 
cpp_sample
cpp_samplecpp_sample
cpp_sample
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기
 
import java-util--- import java-io--- class Vertex { -- Constructo.docx
import java-util--- import java-io---   class Vertex {   -- Constructo.docximport java-util--- import java-io---   class Vertex {   -- Constructo.docx
import java-util--- import java-io--- class Vertex { -- Constructo.docx
 
Create a system to simulate vehicles at an intersection. Assume th.pdf
Create a system to simulate vehicles at an intersection. Assume th.pdfCreate a system to simulate vehicles at an intersection. Assume th.pdf
Create a system to simulate vehicles at an intersection. Assume th.pdf
 
Java serialization
Java serializationJava serialization
Java serialization
 
PersonData.h#ifndef PersonData_h #define PersonData_h#inclu.pdf
 PersonData.h#ifndef PersonData_h #define PersonData_h#inclu.pdf PersonData.h#ifndef PersonData_h #define PersonData_h#inclu.pdf
PersonData.h#ifndef PersonData_h #define PersonData_h#inclu.pdf
 
C#i need help creating the instance of stream reader to read from .pdf
C#i need help creating the instance of stream reader to read from .pdfC#i need help creating the instance of stream reader to read from .pdf
C#i need help creating the instance of stream reader to read from .pdf
 
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
 
Please do Part A, Ill be really gratefulThe main.c is the skeleto.pdf
Please do Part A, Ill be really gratefulThe main.c is the skeleto.pdfPlease do Part A, Ill be really gratefulThe main.c is the skeleto.pdf
Please do Part A, Ill be really gratefulThe main.c is the skeleto.pdf
 
Complete skeletonimport java.util.ArrayList; public class My.pdf
Complete skeletonimport java.util.ArrayList; public class My.pdfComplete skeletonimport java.util.ArrayList; public class My.pdf
Complete skeletonimport java.util.ArrayList; public class My.pdf
 
Production.javapublic class Production {    Declaring instance.pdf
Production.javapublic class Production {    Declaring instance.pdfProduction.javapublic class Production {    Declaring instance.pdf
Production.javapublic class Production {    Declaring instance.pdf
 
Game unleashedjavascript
Game unleashedjavascriptGame unleashedjavascript
Game unleashedjavascript
 
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx
 
infoShare 2014: Gino Marckx, Forget about Agile, let's write great code first!
infoShare 2014: Gino Marckx, Forget about Agile, let's write great code first!infoShare 2014: Gino Marckx, Forget about Agile, let's write great code first!
infoShare 2014: Gino Marckx, Forget about Agile, let's write great code first!
 
C346_PA3_W12srccommonBaseThread.javaC346_PA3_W12srccommonB.docx
C346_PA3_W12srccommonBaseThread.javaC346_PA3_W12srccommonB.docxC346_PA3_W12srccommonBaseThread.javaC346_PA3_W12srccommonB.docx
C346_PA3_W12srccommonBaseThread.javaC346_PA3_W12srccommonB.docx
 
assignmentTwoCar.javaassignmentTwoCar.javapackage assignmentTw.docx
assignmentTwoCar.javaassignmentTwoCar.javapackage assignmentTw.docxassignmentTwoCar.javaassignmentTwoCar.javapackage assignmentTw.docx
assignmentTwoCar.javaassignmentTwoCar.javapackage assignmentTw.docx
 
Modify the bouncing ball example demonstrated/tutorialoutlet
Modify the bouncing ball example demonstrated/tutorialoutletModify the bouncing ball example demonstrated/tutorialoutlet
Modify the bouncing ball example demonstrated/tutorialoutlet
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.
 

More from wkyra78

Melissa HinkhouseWeek 3-Original PostNURS 6050 Policy and A.docx
Melissa HinkhouseWeek 3-Original PostNURS 6050 Policy and A.docxMelissa HinkhouseWeek 3-Original PostNURS 6050 Policy and A.docx
Melissa HinkhouseWeek 3-Original PostNURS 6050 Policy and A.docx
wkyra78
 
Melissa HinkhouseAdvanced Pharmacology NURS-6521N-43Professo.docx
Melissa HinkhouseAdvanced Pharmacology NURS-6521N-43Professo.docxMelissa HinkhouseAdvanced Pharmacology NURS-6521N-43Professo.docx
Melissa HinkhouseAdvanced Pharmacology NURS-6521N-43Professo.docx
wkyra78
 
Meiner, S. E., & Yeager, J. J. (2019). Chapter 17Chap.docx
Meiner, S. E., & Yeager, J. J. (2019).    Chapter 17Chap.docxMeiner, S. E., & Yeager, J. J. (2019).    Chapter 17Chap.docx
Meiner, S. E., & Yeager, J. J. (2019). Chapter 17Chap.docx
wkyra78
 
member is a security software architect in a cloud service provider .docx
member is a security software architect in a cloud service provider .docxmember is a security software architect in a cloud service provider .docx
member is a security software architect in a cloud service provider .docx
wkyra78
 
Melissa ShortridgeWeek 6COLLAPSEMy own attitude has ch.docx
Melissa ShortridgeWeek 6COLLAPSEMy own attitude has ch.docxMelissa ShortridgeWeek 6COLLAPSEMy own attitude has ch.docx
Melissa ShortridgeWeek 6COLLAPSEMy own attitude has ch.docx
wkyra78
 
Melissa is a 15-year-old high school student. Over the last week.docx
Melissa is a 15-year-old high school student. Over the last week.docxMelissa is a 15-year-old high school student. Over the last week.docx
Melissa is a 15-year-old high school student. Over the last week.docx
wkyra78
 
Measurement  of  the  angle  θ          .docx
Measurement  of  the  angle  θ          .docxMeasurement  of  the  angle  θ          .docx
Measurement  of  the  angle  θ          .docx
wkyra78
 
Measurement of the angle θ For better understanding .docx
Measurement of the angle θ     For better understanding .docxMeasurement of the angle θ     For better understanding .docx
Measurement of the angle θ For better understanding .docx
wkyra78
 
Meaning-Making Forum 2 (Week 5)Meaning-Making Forums 1-4 are thi.docx
Meaning-Making Forum 2 (Week 5)Meaning-Making Forums 1-4 are thi.docxMeaning-Making Forum 2 (Week 5)Meaning-Making Forums 1-4 are thi.docx
Meaning-Making Forum 2 (Week 5)Meaning-Making Forums 1-4 are thi.docx
wkyra78
 
MBA6231 - 1.1 - project charter.docxProject Charter Pr.docx
MBA6231 - 1.1 - project charter.docxProject Charter Pr.docxMBA6231 - 1.1 - project charter.docxProject Charter Pr.docx
MBA6231 - 1.1 - project charter.docxProject Charter Pr.docx
wkyra78
 
Medication Errors Led to Disastrous Outcomes1. Search th.docx
Medication Errors Led to Disastrous Outcomes1. Search th.docxMedication Errors Led to Disastrous Outcomes1. Search th.docx
Medication Errors Led to Disastrous Outcomes1. Search th.docx
wkyra78
 
Meet, call, Skype or Zoom with a retired athlete and interview himh.docx
Meet, call, Skype or Zoom with a retired athlete and interview himh.docxMeet, call, Skype or Zoom with a retired athlete and interview himh.docx
Meet, call, Skype or Zoom with a retired athlete and interview himh.docx
wkyra78
 
Medication Administration Make a list of the most common med.docx
Medication Administration Make a list of the most common med.docxMedication Administration Make a list of the most common med.docx
Medication Administration Make a list of the most common med.docx
wkyra78
 
media portfolio”about chapter 1 to 15 from the book  Ci.docx
media portfolio”about chapter 1 to 15 from the book  Ci.docxmedia portfolio”about chapter 1 to 15 from the book  Ci.docx
media portfolio”about chapter 1 to 15 from the book  Ci.docx
wkyra78
 
MediationNameAMUDate.docx
MediationNameAMUDate.docxMediationNameAMUDate.docx
MediationNameAMUDate.docx
wkyra78
 
Media coverage influences the publics perception of the crimina.docx
Media coverage influences the publics perception of the crimina.docxMedia coverage influences the publics perception of the crimina.docx
Media coverage influences the publics perception of the crimina.docx
wkyra78
 
Media Content AnalysisPurpose Evaluate the quality and value of.docx
Media Content AnalysisPurpose Evaluate the quality and value of.docxMedia Content AnalysisPurpose Evaluate the quality and value of.docx
Media Content AnalysisPurpose Evaluate the quality and value of.docx
wkyra78
 
Mayan gods and goddesses are very much a part of this text.  Their i.docx
Mayan gods and goddesses are very much a part of this text.  Their i.docxMayan gods and goddesses are very much a part of this text.  Their i.docx
Mayan gods and goddesses are very much a part of this text.  Their i.docx
wkyra78
 
Media and SocietyIn 1,100 words, complete the followingAn.docx
Media and SocietyIn 1,100 words, complete the followingAn.docxMedia and SocietyIn 1,100 words, complete the followingAn.docx
Media and SocietyIn 1,100 words, complete the followingAn.docx
wkyra78
 
MBA 5110 – Business Organization and ManagementMidterm ExamAns.docx
MBA 5110 – Business Organization and ManagementMidterm ExamAns.docxMBA 5110 – Business Organization and ManagementMidterm ExamAns.docx
MBA 5110 – Business Organization and ManagementMidterm ExamAns.docx
wkyra78
 

More from wkyra78 (20)

Melissa HinkhouseWeek 3-Original PostNURS 6050 Policy and A.docx
Melissa HinkhouseWeek 3-Original PostNURS 6050 Policy and A.docxMelissa HinkhouseWeek 3-Original PostNURS 6050 Policy and A.docx
Melissa HinkhouseWeek 3-Original PostNURS 6050 Policy and A.docx
 
Melissa HinkhouseAdvanced Pharmacology NURS-6521N-43Professo.docx
Melissa HinkhouseAdvanced Pharmacology NURS-6521N-43Professo.docxMelissa HinkhouseAdvanced Pharmacology NURS-6521N-43Professo.docx
Melissa HinkhouseAdvanced Pharmacology NURS-6521N-43Professo.docx
 
Meiner, S. E., & Yeager, J. J. (2019). Chapter 17Chap.docx
Meiner, S. E., & Yeager, J. J. (2019).    Chapter 17Chap.docxMeiner, S. E., & Yeager, J. J. (2019).    Chapter 17Chap.docx
Meiner, S. E., & Yeager, J. J. (2019). Chapter 17Chap.docx
 
member is a security software architect in a cloud service provider .docx
member is a security software architect in a cloud service provider .docxmember is a security software architect in a cloud service provider .docx
member is a security software architect in a cloud service provider .docx
 
Melissa ShortridgeWeek 6COLLAPSEMy own attitude has ch.docx
Melissa ShortridgeWeek 6COLLAPSEMy own attitude has ch.docxMelissa ShortridgeWeek 6COLLAPSEMy own attitude has ch.docx
Melissa ShortridgeWeek 6COLLAPSEMy own attitude has ch.docx
 
Melissa is a 15-year-old high school student. Over the last week.docx
Melissa is a 15-year-old high school student. Over the last week.docxMelissa is a 15-year-old high school student. Over the last week.docx
Melissa is a 15-year-old high school student. Over the last week.docx
 
Measurement  of  the  angle  θ          .docx
Measurement  of  the  angle  θ          .docxMeasurement  of  the  angle  θ          .docx
Measurement  of  the  angle  θ          .docx
 
Measurement of the angle θ For better understanding .docx
Measurement of the angle θ     For better understanding .docxMeasurement of the angle θ     For better understanding .docx
Measurement of the angle θ For better understanding .docx
 
Meaning-Making Forum 2 (Week 5)Meaning-Making Forums 1-4 are thi.docx
Meaning-Making Forum 2 (Week 5)Meaning-Making Forums 1-4 are thi.docxMeaning-Making Forum 2 (Week 5)Meaning-Making Forums 1-4 are thi.docx
Meaning-Making Forum 2 (Week 5)Meaning-Making Forums 1-4 are thi.docx
 
MBA6231 - 1.1 - project charter.docxProject Charter Pr.docx
MBA6231 - 1.1 - project charter.docxProject Charter Pr.docxMBA6231 - 1.1 - project charter.docxProject Charter Pr.docx
MBA6231 - 1.1 - project charter.docxProject Charter Pr.docx
 
Medication Errors Led to Disastrous Outcomes1. Search th.docx
Medication Errors Led to Disastrous Outcomes1. Search th.docxMedication Errors Led to Disastrous Outcomes1. Search th.docx
Medication Errors Led to Disastrous Outcomes1. Search th.docx
 
Meet, call, Skype or Zoom with a retired athlete and interview himh.docx
Meet, call, Skype or Zoom with a retired athlete and interview himh.docxMeet, call, Skype or Zoom with a retired athlete and interview himh.docx
Meet, call, Skype or Zoom with a retired athlete and interview himh.docx
 
Medication Administration Make a list of the most common med.docx
Medication Administration Make a list of the most common med.docxMedication Administration Make a list of the most common med.docx
Medication Administration Make a list of the most common med.docx
 
media portfolio”about chapter 1 to 15 from the book  Ci.docx
media portfolio”about chapter 1 to 15 from the book  Ci.docxmedia portfolio”about chapter 1 to 15 from the book  Ci.docx
media portfolio”about chapter 1 to 15 from the book  Ci.docx
 
MediationNameAMUDate.docx
MediationNameAMUDate.docxMediationNameAMUDate.docx
MediationNameAMUDate.docx
 
Media coverage influences the publics perception of the crimina.docx
Media coverage influences the publics perception of the crimina.docxMedia coverage influences the publics perception of the crimina.docx
Media coverage influences the publics perception of the crimina.docx
 
Media Content AnalysisPurpose Evaluate the quality and value of.docx
Media Content AnalysisPurpose Evaluate the quality and value of.docxMedia Content AnalysisPurpose Evaluate the quality and value of.docx
Media Content AnalysisPurpose Evaluate the quality and value of.docx
 
Mayan gods and goddesses are very much a part of this text.  Their i.docx
Mayan gods and goddesses are very much a part of this text.  Their i.docxMayan gods and goddesses are very much a part of this text.  Their i.docx
Mayan gods and goddesses are very much a part of this text.  Their i.docx
 
Media and SocietyIn 1,100 words, complete the followingAn.docx
Media and SocietyIn 1,100 words, complete the followingAn.docxMedia and SocietyIn 1,100 words, complete the followingAn.docx
Media and SocietyIn 1,100 words, complete the followingAn.docx
 
MBA 5110 – Business Organization and ManagementMidterm ExamAns.docx
MBA 5110 – Business Organization and ManagementMidterm ExamAns.docxMBA 5110 – Business Organization and ManagementMidterm ExamAns.docx
MBA 5110 – Business Organization and ManagementMidterm ExamAns.docx
 

Recently uploaded

REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdfREASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
giancarloi8888
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
Himanshu Rai
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Fajar Baskoro
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
HajraNaeem15
 
math operations ued in python and all used
math operations ued in python and all usedmath operations ued in python and all used
math operations ued in python and all used
ssuser13ffe4
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
Temple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation resultsTemple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation results
Krassimira Luka
 
B. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdfB. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdf
BoudhayanBhattachari
 
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptxRESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
zuzanka
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
Katrina Pritchard
 
Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...
PsychoTech Services
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
RAHUL
 
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
Nguyen Thanh Tu Collection
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) CurriculumPhilippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
MJDuyan
 
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
imrankhan141184
 
Bonku-Babus-Friend by Sathyajith Ray (9)
Bonku-Babus-Friend by Sathyajith Ray  (9)Bonku-Babus-Friend by Sathyajith Ray  (9)
Bonku-Babus-Friend by Sathyajith Ray (9)
nitinpv4ai
 
Nutrition Inc FY 2024, 4 - Hour Training
Nutrition Inc FY 2024, 4 - Hour TrainingNutrition Inc FY 2024, 4 - Hour Training
Nutrition Inc FY 2024, 4 - Hour Training
melliereed
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 

Recently uploaded (20)

REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdfREASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
 
math operations ued in python and all used
math operations ued in python and all usedmath operations ued in python and all used
math operations ued in python and all used
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
Temple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation resultsTemple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation results
 
B. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdfB. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdf
 
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptxRESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
 
Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
 
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) CurriculumPhilippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
 
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
 
Bonku-Babus-Friend by Sathyajith Ray (9)
Bonku-Babus-Friend by Sathyajith Ray  (9)Bonku-Babus-Friend by Sathyajith Ray  (9)
Bonku-Babus-Friend by Sathyajith Ray (9)
 
Nutrition Inc FY 2024, 4 - Hour Training
Nutrition Inc FY 2024, 4 - Hour TrainingNutrition Inc FY 2024, 4 - Hour Training
Nutrition Inc FY 2024, 4 - Hour Training
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 

proj6Collision.javaproj6Collision.javapackage proj6;import.docx

  • 1. proj6/Collision.javaproj6/Collision.javapackage proj6; import java.util.ArrayList; /** * Collision objects represent individual collisions occuring on NYC streets. * Each object contains information regarding the time, location , number * of injuries and fatalities and types of involved vehicles. * @author Joanna K. * */ publicclassCollisionimplementsComparable<Collision>{ staticprivateSortOrder sortOrder =SortOrder.ZIP; privateString date; privateString time; privateString borough; privateString zip; privateint personsInjured; privateint personsKilled; privateint pedestriansInjured; privateint pedestriansKilled; privateint cyclistsInjured; privateint cyclistsKilled; privateint motoristsInjured; privateint motoristsKilled; privateString vehicleCode1; privateString vehicleCode2; privateString uniqueKey;
  • 2. /** * Creates a Collision object given an array of entries. * There should be 21 string entries in the following order: * date * time * borough * zip * lattitude^ * longitude ^ * on street name^ * cross street name ^ * personsInjured * personsKilled * pedestriansInjured * pedestriansKilled * cyclistsInjured * cyclistsKilled * motoristsInjured * motoristsKilled * contributing factor vehicle 1^ * contributing factor vehicle 2^ * uniqueKey * vehicleCode1 * vehicleCode2 * The entries indicated with ^ are not used. * * @param entries an array of entries containing information about the * collision * @throws IllegalArgumentException when the Collision obj ect cannot be created * due to errors or incompleteness of the entries parameter */
  • 3. publicCollision(ArrayList<String> entries )throwsIllegalArgum entException{ date = entries.get(0); time = entries.get(1); borough = entries.get(2); zip = entries.get(3); if(!verifyZip(zip)){ thrownewIllegalArgumentException("invalid zip"); } try{ personsInjured =Integer.parseInt(entries.get(8)); personsKilled =Integer.parseInt(entries.get(9)); pedestriansInjured =Integer.parseInt(entries.get(10)); pedestriansKilled =Integer.parseInt(entries.get(11)); cyclistsInjured =Integer.parseInt(entries.get(12)); cyclistsKilled =Integer.parseInt(entries.get(13)); motoristsInjured =Integer.parseInt(entries.get(14)); motoristsKilled =Integer.parseInt(entries.get(15)); } catch(NumberFormatException ex ){ thrownewIllegalArgumentException( ex.getMessage()); } uniqueKey = entries.get(18); vehicleCode1 = entries.get(19); vehicleCode2 = entries.get(20); } /* * Verifies accuracy of the zip code. * @param zip the zip code to be verified * @return true if zip is a valid zip code, false otherwise */ privateboolean verifyZip (String zip ){
  • 4. if( zip.length()!=5)returnfalse; for(int i =0; i < zip.length(); i++){ if(!Character.isDigit( zip.charAt(i))){ returnfalse; } } returntrue; } /** * Computes and returns string representation of this Collisio n object. * @see java.lang.Object#toString() */ @Override publicString toString(){ return"Collision [date="+ date +", time="+ time +", borough="+ borough +", zip="+ zip +", personsInjured="+ personsInjured +", personsKilled="+ pers onsKilled +", pedestriansInjured=" + pedestriansInjured +", pedestriansKilled="+ pedestriansKilled +", cyclistsInjured=" + cyclistsInjured +", cyclistsKilled="+ cyclistsKilled +", motori stsInjured="+ motoristsInjured +", motoristsKilled="+ motoristsKilled +", vehicleCode1="+ ve hicleCode1 +", vehicleCode2=" + vehicleCode2 +", uniqueKey="+ uniqueKey +"]"; } /** * Set the sort order for Collision objects to be one of the all owed values by the SortOrder enumerator. * @param sortOrder the sortOrder to set
  • 5. */ publicstaticvoid setSortOrder(SortOrder sortOrder){ Collision.sortOrder = sortOrder; } /** * Compares two Collision objects based on their zip code, n umber of cyclist-injuries or * number of person- injuries. The comparison is determined by the value of a flag set by * setSortOrder() method. * @see java.lang.Comparable#compareTo(java.lang.Object) */ @Override publicint compareTo(Collision other){ if( sortOrder ==SortOrder.ZIP ){ returnthis.zip.compareTo(other.zip); } elseif(sortOrder ==SortOrder.CYCLISTS){ return((this.cyclistsInjured +this.cyclistsKilled) -(other.cyclistsInjured +this.cyclistsKilled )); } elseif(sortOrder ==SortOrder.PERSONS){ return((this.personsInjured +this.personsKilled) -(other.personsInjured +this.personsKilled )); } return0; } /** * Return the time of this Collision object. * @return the time */ publicString getTime(){ return time;
  • 6. } /** * Return the zip code of this Collision object. * @return the zip */ publicString getZip(){ return zip; } /** * Return the number of injured cyclists of this Collision obje ct. * @return the cyclistsInjured */ publicint getCyclistsInjured(){ return cyclistsInjured; } /** * Return the number of killed cyclists of this Collision objec t. * @return the cyclistsKilled */ publicint getCyclistsKilled(){ return cyclistsKilled; } /** * Return the number of injured persons of this Collision obje ct. * @return the personsInjured */ publicint getPersonsInjured(){ return personsInjured; }
  • 7. /** * Return the number of killed persons of this Collision objec t. * @return the personsKilled */ publicint getPersonsKilled(){ return personsKilled; } /** * Return the number of injured pedestrians of this Collision object. * @return the pedestriansInjured */ publicint getPedestriansInjured(){ return pedestriansInjured; } /** * Return the number of killed pedestrians of this Collision o bject. * @return the pedestriansKilled */ publicint getPedestriansKilled(){ return pedestriansKilled; } /** * Return the number of injured motorists of this Collision ob ject. * @return the motoristsInjured */ publicint getMotoristsInjured(){
  • 8. return motoristsInjured; } /** * Return the number of killed motorists of this Collision obj ect. * @return the motoristsKilled */ publicint getMotoristsKilled(){ return motoristsKilled; } /** * Return the vehicle 1 of this Collision object. * @return the vehicleCode1 */ publicString getVehicleCode1(){ return vehicleCode1; } /** * Return the vehicle 2 of this Collision object. * @return the vehicleCode2 */ publicString getVehicleCode2(){ return vehicleCode2; } } proj6/CollisionInfo.javaproj6/CollisionInfo.java
  • 9. package proj6; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; /** * This is a program that computes some information about the d ata posted by * OpenNYC regarding the collision records on the streets of N YC. * * @author Joanna K. * */ publicclassCollisionInfo{ /** * The main method that starts the program. It is responsible for opening and reading the * input file, creating the CollisionList object and using it co mpute the * predetermined results. * @param args the array should contain the name of the inpu t file as the first element, * all other elements are ignored * @throws FileNotFoundException if the input file is corrup ted or vanishes during the * execution of this program */ publicstaticvoid main(String[] args)throwsFileNotFoundExcepti on{ finalint NUM_OF_ENTRIES =21; long startTimer, elapsedTime1, elapsedTime2;
  • 10. startTimer =System.nanoTime(); if(args.length <1){ System.err.println("File name missing"); System.exit(0); } File fileName =newFile(args[0]); if(!fileName.canRead()){ System.err.printf("Cannot read from file %sn.", fileName.getA bsolutePath()); System.exit(0); } Scanner fin =newScanner(fileName); CollisionList list =newCollisionList(); while( fin.hasNextLine()){ String textLine = fin.nextLine(); ArrayList<String> words = split (textLine ); if(words.size()!= NUM_OF_ENTRIES){ continue;//skip lines that are not complete } list.add(words); } elapsedTime1 =System.nanoTime()- startTimer; startTimer =System.nanoTime(); //task 1 System.out.println("ZIP codes with the largest number of collisi ons:");
  • 11. System.out.println( list.getZipCodesWithMostCollisions(3)); //task2 System.out.println("ZIP codes with the fewest number of collisi ons:"); System.out.println( list.getZipCodesWithLeastCollisions(3)); //task 3 System.out.println("ZIP codes with the most injuries and fataliti es (combined):"); System.out.println( list.getZipCodesWithMostPersonIncidents(3 )); //task 4 System.out.println("ZIP codes with the most cyclist injuries and fatalities:"); System.out.println( list.getZipCodesWithMostCyclistIncidents(3 )); //task5: System.out.println("Percentage of collisions involving certain v ehicle type:"); System.out.println(list.getVehicleTypeStats()); //task6: System.out.println("Fraction of collisions by hour:"); System.out.println(list.getHourlyStats()); elapsedTime2 =System.nanoTime()- startTimer; System.out.println("nn============================= ===============n"); System.out.printf("Reading and storing data: %,15d nanosecond sn", elapsedTime1); System.out.printf("Computation of results : %,15d nanoseconds n", elapsedTime2);
  • 12. fin.close(); } /** * Splits a given line according to commas (commas within e ntries are ignored) * @param textLine line of text to be parsed * @return an ArrayList object containing all individual entri es/tokens * found on the line. */ publicstaticArrayList<String> split (String textLine ){ ArrayList<String> entries =newArrayList<String>(); int lineLength = textLine.length(); StringBuffer nextWord =newStringBuffer(); char nextChar; boolean insideQuotes =false; for(int i =0; i < lineLength; i++){ nextChar = textLine.charAt(i); //add character to the current entry if( nextChar !=','&& nextChar !='"'){ nextWord.append( nextChar ); } //double quote found, decide if it is opening or closing one elseif(nextChar =='"'){ if( insideQuotes ){ insideQuotes =false; } else{ insideQuotes =true; } }
  • 13. //found comma inside double quotes, just add it to the string elseif(nextChar ==','&& insideQuotes){ nextWord.append( nextChar ); } //end of the current entry reached, add it to the list of entries //and reset the nextWord to empty string elseif(nextChar ==','&&!insideQuotes){ //trim the white space before adding to the list entries.add( nextWord.toString().trim()); nextWord =newStringBuffer(); } else{ System.err.println("This should never be printed.n"); } } //add the last word //trim the white space before adding to the list entries.add( nextWord.toString().trim()); return entries; } } proj6/CollisionList.javaproj6/CollisionList.javapackage proj6; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; /** * CollisionList class stores a list of collisions. The organizatio
  • 14. n of this list is * based on the zip code associated with a given collision. This organization simplifies * processing of collisions that occur within a particular zip cod e. * @author Joanna K. */ publicclassCollisionList{ privateArrayList<ZipCodeList> list; /** * Creates an empty CollisionList object. */ publicCollisionList(){ list =newArrayList<ZipCodeList>(); } /** * Adds a particular record to this CollisionList object. * The record should consist of 21 string entries in the follow ing order: * date * time * borough * zip * lattitude^ * longitude ^ * on street name^ * cross street name ^ * personsInjured * personsKilled * pedestriansInjured * pedestriansKilled
  • 15. * cyclistsInjured * cyclistsKilled * motoristsInjured * motoristsKilled * contributing factor vehicle 1^ * contributing factor vehicle 2^ * uniqueKey * vehicleCode1 * vehicleCode2 * The entries indicated with ^ are not used. * * @param record an list of string describing a particular coll ision (see above * for order of entries) * @return true if the record was added to this CollisionList object, false if any * problem occurred and the record was not added */ publicboolean add (ArrayList<String> record ){ try{ Collision col =newCollision(record); ZipCodeList tmp =newZipCodeList(col); int index = list.indexOf(tmp); if(index >=0){//add the collision object to the existing zip code list list.get(index).add(col); } else{//add the new zip code list list.add(tmp); } } catch(IllegalArgumentException ex ){ returnfalse;//return false if the Collision constructor failed }
  • 16. returntrue;//return true to indicate that the object was added } /** * Determines k zip codes with most collisions in this Collisi onList object. * @param k number of zip codes with the highest number of collisions * @return a string formatted as * zip numOfCollisions * one per line, that contains k zip codes with the highest nu mber of collisions */ publicString getZipCodesWithMostCollisions (int k){ @SuppressWarnings("unchecked") ArrayList<ZipCodeList> sortedList =(ArrayList<ZipCodeList>) list.clone(); //sort the list Collections.sort(sortedList,newCompareByNumOfCollisionsDes cending()); StringBuffer result =newStringBuffer(); int count =0; for(int i =0; i < k && i < sortedList.size()&& count<sortedList. size(); i++){ do{ result.append(String.format(" %5s %5d collisions n",sortedList.get(count).getZip(), sortedList.get(count).getTotalNumOfCollisions())) ; count++; }while( count+1< sortedList.size()
  • 17. && sortedList.get(count).getTotalNumOfCollisions() == sortedList.get(count+1).getTotalNumOfCollisions()); } return result.toString(); } /** * Determines k zip codes with least collisions in this Collisi onList object. * @param k number of zip codes with the lowest number of collisions * @return a string formatted as * zip numOfCollisions * one per line, that contains k zip codes with the lowest nu mber of collisions */ publicString getZipCodesWithLeastCollisions (int k){ @SuppressWarnings("unchecked") ArrayList<ZipCodeList> sortedList =(ArrayList<ZipCodeList>) list.clone(); //sort the list Collections.sort(sortedList,newCompareByNumOfCollisionsAsc ending()); StringBuffer result =newStringBuffer(); int count =0; for(int i =0; i < k && i < sortedList.size()&& count<sortedList. size(); i++){ do{ result.insert(0,String.format(" %5s %5d collisions n",sortedList.get(count).getZip(), sortedList.get(count).getTotalNumOfCollisions()))
  • 18. ; count++; }while( count+1< sortedList.size() && sortedList.get(count).getTotalNumOfCollisions() == sortedList.get(count+1).getTotalNumOfCollisions()); } return result.toString(); } /** * Determines k zip codes with most number of collisions inv olving * cyclists in this CollisionList object. * @param k number of zip codes with the highest number of collisions that involved cyclists * @return a string formatted as * zip numOfCycliststHurt (numOfCyclists killed) * one per line, that contains k zip codes with the highest nu mber of injured cyclists */ publicString getZipCodesWithMostCyclistIncidents (int k ){ @SuppressWarnings("unchecked") ArrayList<ZipCodeList> sortedList =(ArrayList<ZipCodeList>) list.clone(); //sort the list CompareByNumOfCyclistsIncidentsDescending comp =newCom pareByNumOfCyclistsIncidentsDescending(); Collections.sort(sortedList, comp ); StringBuffer result =newStringBuffer(); int inj =0, killed =0;
  • 19. int count =0; for(int i =0; i < k && i < sortedList.size()&& count< sortedList. size(); i++){ do{ inj = sortedList.get(count).getTotalNumOfCyclistsInj ured(); killed = sortedList.get(count).getTotalNumOfCyclist sKilled(); result.append(String.format(" %5s %5d (%3d kille d ) cyclists hurtn", sortedList.get(count).getZip(), inj + killed, killed )); count++; } while( count+1< sortedList.size() &&0== comp.compare(sortedList.get(count), sortedList.get(cou nt+1))); } return result.toString(); } /** * Determines k zip codes with most number of injured and ki lled persons. * @param k number of zip codes with the highest number of injured and killed persons * @return a string formatted as * zip numOfPersonsHurt (numOfPersons killed) * one per line, that contains k zip codes with the highest nu mber of injured persons */ publicString getZipCodesWithMostPersonIncidents (int k ){ @SuppressWarnings("unchecked")
  • 20. ArrayList<ZipCodeList> sortedList =(ArrayList<ZipCodeList>) list.clone(); //sort the list CompareByNumOfPersonsIncidentsDescending comp =newCom pareByNumOfPersonsIncidentsDescending(); Collections.sort(sortedList, comp ); StringBuffer result =newStringBuffer(); int inj =0, killed =0; int count =0; for(int i =0; i < k && i < sortedList.size()&& count< sortedList. size(); i++){ do{ inj = sortedList.get(count).getTotalNumOfPersonsInj ured(); killed = sortedList.get(count).getTotalNumOfPerson sKilled(); result.append(String.format(" %5s %5d (%3d kille d ) persons hurtn", sortedList.get(count).getZip(), inj + killed, killed )); count++; } while( count+1< sortedList.size() &&0== comp.compare(sortedList.get(count), sortedList.get(cou nt+1))); } return result.toString(); } /** * Computes percentage of total collisions in this CollisionLi st object that involved one
  • 21. * of the following vehicle types: taxi, bus, bicycle, truck, fir e truck and ambulance. * @return a string containing the results of the computation */ publicString getVehicleTypeStats (){ String result =newString(); int taxi =0; int bus =0; int bicycle =0; int fireTruck =0; int ambulance =0; int totalNumOfCollisions =0; for(ZipCodeList l : list ){ totalNumOfCollisions += l.getTotalNumOfCollisions(); for(Collision c : l ){ if(c.getVehicleCode1().equalsIgnoreCase("taxi")|| c.getVehicleCode2().equalsIgnoreCase("taxi")) taxi++; if(c.getVehicleCode1().equalsIgnoreCase("bus")|| c.getVehicleCode2().equalsIgnoreCase("bus")) bus++; if(c.getVehicleCode1().equalsIgnoreCase("bicycle")|| c.getVehicleCode2().equalsIgnoreCase("bicycle ")) bicycle++; if(c.getVehicleCode1().equalsIgnoreCase("fire truck")|| c.getVehicleCode2().equalsIgnoreCase("fire tru ck")) fireTruck++; if(c.getVehicleCode1().equalsIgnoreCase("ambulance")|| c.getVehicleCode2().equalsIgnoreCase("ambula nce")) ambulance++; } }
  • 22. //create a string object with results result +=String.format(" %- 11s %5.2f%%n","taxi",(float)(taxi)/totalNumOfCollisions*100) ; result +=String.format(" %- 11s %5.2f%%n","bus",(float)(bus)/totalNumOfCollisions*100); result +=String.format(" %- 11s %5.2f%%n","bicycle",(float)(bicycle)/totalNumOfCollision s*100); result +=String.format(" %- 11s %5.2f%%n","fire truck",(float)(fireTruck)/totalNumOfColl isions*100); result +=String.format(" %- 11s %5.2f%%n","ambulance",(float)(ambulance)/totalNumOfC ollisions*100); return result; } /** * Computes percentage of total collisions in this CollisionLi st object that occured within * a particular hour. The collisions are placed into bins of 1 h our intervals. * @return a string containing the results of the computation */ publicString getHourlyStats (){ StringBuffer result =newStringBuffer(); //counter for each hour int[] hourlyCount =newint[24]; String hour ="", time =""; StringBuffer bar; int totalNumOfCollisions =0;
  • 23. for(ZipCodeList l : list ){ totalNumOfCollisions += l.getTotalNumOfCollisions(); for(Collision c : l ){ try{ //extract the hour from the time entry time = c.getTime(); hour = time.substring(0,time.indexOf(':')).trim(); //increment counter for that hour hourlyCount[Integer.parseInt(hour)]++; }catch(IndexOutOfBoundsException e){ //ignore incorrectly formed times }catch(NumberFormatException e ){ //ignore incorrectly formed times } } } for(int i =0; i <24; i++){ //determine number of "bars" to be printed for visual representat ion of //the histogram int numOfBars =(int)(((double)hourlyCount[i]/totalNumOfColli sions)*240); bar =newStringBuffer(numOfBars); for(int j =0; j < numOfBars; j++) bar.append("|"); result.append(String.format("%3d h %5.1f%% %s%n", i,100.0*hourlyCount[i]/totalNumOfCollisions, bar. toString())); } return result.toString(); } }
  • 24. /* * Comparator class for comparing two @see ZipCodeList objec ts based on the * number of collisions occurring in each. The resulting order is ascending. * @author Joanna K. * */ classCompareByNumOfCollisionsAscendingimplementsCompar ator<ZipCodeList>{ /* (non-Javadoc) * @see java.util.Comparator#compare(java.lang.Object, java .lang.Object) */ @Override publicint compare(ZipCodeList arg0,ZipCodeList arg1){ return arg0.getTotalNumOfCollisions()- arg1.getTotalNumOfCollisions(); } } /* * Comparator class for comparing two @see ZipCodeList objec ts based on the * number of collisions occurring in each. The resulting order is descending. * @author Joanna K. * */ classCompareByNumOfCollisionsDescendingimplementsCompa rator<ZipCodeList>{
  • 25. /* (non-Javadoc) * @see java.util.Comparator#compare(java.lang.Object, java .lang.Object) */ @Override publicint compare(ZipCodeList arg0,ZipCodeList arg1){ return arg1.getTotalNumOfCollisions()- arg0.getTotalNumOfCollisions(); } } /* * Comparator class for comparing two @see ZipCodeList objec ts based on the * number of injured persons. The resulting order is descending. Ties are resolved * based on the number of killed persons. * @author Joanna K. * */ classCompareByNumOfPersonsIncidentsDescendingimplements Comparator<ZipCodeList>{ @Override publicint compare(ZipCodeList arg0,ZipCodeList arg1){ int diff =( arg1.getTotalNumOfPersonsInjured()+ arg1.getTotal NumOfPersonsKilled()) - ( arg0.getTotalNumOfPersonsInjured()+ arg0.getTotalNumOfPe rsonsKilled()); if(diff !=0) return diff; elsereturn( arg1.getTotalNumOfPersonsKilled()- arg0.getTotalNumOfPersonsKilled());
  • 26. } } /* * Comparator class for comparing two @see ZipCodeList objec ts based on the * number of injured persons. The resulting order is ascending. Ties are resolved * based on the number of killed persons. * @author Joanna K. * */ classCompareByNumOfPersonsIncidentsAscendingimplementsC omparator<ZipCodeList>{ @Override publicint compare(ZipCodeList arg0,ZipCodeList arg1){ int diff =- ( arg1.getTotalNumOfPersonsInjured()+ arg1.getTotalNumOfPe rsonsKilled()) +( arg0.getTotalNumOfPersonsInjured()+ arg0.getTotalNumOfP ersonsKilled()); if(diff !=0) return diff; elsereturn(- arg1.getTotalNumOfPersonsKilled()+ arg0.getTotalNumOfPerso nsKilled()); } } /* * Comparator class for comparing two @see ZipCodeList objec ts based on the
  • 27. * number of injured cyclists. The resulting order is descending. Ties are resolved * based on the number of killed cyclists. * @author Joanna K. * */ classCompareByNumOfCyclistsIncidentsDescendingimplements Comparator<ZipCodeList>{ @Override publicint compare(ZipCodeList arg0,ZipCodeList arg1){ int diff =( arg1.getTotalNumOfCyclistsInjured()+ arg1.getTotal NumOfCyclistsKilled()) - ( arg0.getTotalNumOfCyclistsInjured()+ arg0.getTotalNumOfC yclistsKilled()); if(diff !=0) return diff; elsereturn( arg1.getTotalNumOfCyclistsKilled()- arg0.getTotalNumOfCyclistsKilled()); } } /* * Comparator class for comparing two @see ZipCodeList objec ts based on the * number of injured cyclists. The resulting order is ascending. Ties are resolved * based on the number of killed cyclists. * @author Joanna K. * */ classCompareByNumOfCyclistsIncidentsAscendingimplementsC omparator<ZipCodeList>{
  • 28. @Override publicint compare(ZipCodeList arg0,ZipCodeList arg1){ int diff =- ( arg1.getTotalNumOfCyclistsInjured()+ arg1.getTotalNumOfC yclistsKilled()) +( arg0.getTotalNumOfCyclistsInjured()+ arg0.getTotalNumOf CyclistsKilled()); if(diff !=0) return diff; elsereturn(- arg1.getTotalNumOfCyclistsKilled()+ arg0.getTotalNumOfCycl istsKilled()); } } proj6/SortOrder.javaproj6/SortOrder.javapackage proj6; /** * Enumerator used to decide on sort order of Collision objects. * @author Joanna K. * */ enum SortOrder{ ZIP, CYCLISTS, PERSONS} proj6/ZipCodeList.javaproj6/ZipCodeList.javapackage proj6; import java.util.ArrayList; import java.util.Iterator; /** * ZipCodeList contains collision objects that all occured in the
  • 29. same zip * code. It keeps track of additional information like total numb er of * collisions, injuries and fatalities. * @author Joanna K. * */ publicclassZipCodeListimplementsIterable<Collision>,Compara ble<ZipCodeList>{ privateArrayList<Collision> list; privateString zip; privateint totalNumOfCollisions; privateint totalNumOfPersonsInjured; privateint totalNumOfPersonsKilled; privateint totalNumOfCyclistsInjured; privateint totalNumOfCyclistsKilled; privateint totalNumOfPedestriansInjured; privateint totalNumOfPedestriansKilled; privateint totalNumOfMotoristsInjured; privateint totalNumOfMotoristsKilled; /** * Creates a ZipCodeList objects based on the first collision. The * zip code for this ZipCodeList is set to the zip code * associated with the collision col. * @param col the initial collisions for this ZipCodeList obje ct */ publicZipCodeList(Collision col ){ list =newArrayList<Collision>(); zip = col.getZip(); add(col);
  • 30. } /** * Adds another Collision object to this ZipCodeList object. * @param col a Collision object to be added to this ZipCode List object * @throws IllegalArgumentException when the zip code of t he new Collision * object col is not the same as the zip code for this ZipCode List object */ publicvoid add (Collision col)throwsIllegalArgumentException{ if(col ==null)return; if(!col.getZip().equals(zip)) thrownewIllegalArgumentException("Error: zip codes are not m atching. "); list.add(col); totalNumOfCollisions ++; totalNumOfPersonsInjured += col.getPersonsInjured(); totalNumOfPersonsKilled += col.getPersonsKilled(); totalNumOfCyclistsInjured += col.getCyclistsInjured(); totalNumOfCyclistsKilled += col.getCyclistsKilled(); totalNumOfPedestriansInjured += col.getPedestriansInjure d(); totalNumOfPedestriansKilled += col.getPedestriansKilled( ); totalNumOfMotoristsInjured += col.getMotoristsInjured(); totalNumOfMotoristsKilled += col.getMotoristsKilled(); } /** * Returns an iterator for this ZipCodeList object. * @see java.lang.Iterable#iterator()
  • 31. */ @Override publicIterator<Collision> iterator(){ return list.iterator(); } /** * Computes the hash code for this ZipCodeList object. The h ashcode * is based on the zip code associated with this object. * @see java.lang.Object#hashCode() */ @Override publicint hashCode(){ finalint prime =31; int result =1; result = prime * result +((zip ==null)?0: zip.hashCode()); return result; } /** * Returns true if this ZipCodeList object and the parameter h ave the * same zip code associated with them. Returns false otherwis e. * @see java.lang.Object#equals(java.lang.Object) */ @Override publicboolean equals(Object obj){ if(this== obj) returntrue; if(obj ==null) returnfalse; if(getClass()!= obj.getClass())
  • 32. returnfalse; ZipCodeList other =(ZipCodeList) obj; if(zip ==null){ if(other.zip !=null) returnfalse; }elseif(!zip.equals(other.zip)) returnfalse; returntrue; } /** * Compares two ZioCodeList objects based on the zip code v alue stored in them. * The results are based on string comparison of the two zip c odes. * @see java.lang.Comparable#compareTo(java.lang.Object) * Compares two ZipCodeList objects based on the zip codes. */ @Override publicint compareTo(ZipCodeList o){ return zip.compareTo(o.zip); } /** * Returns the zip code of this ZipCodeList object * @return the zip */ publicString getZip(){ return zip; } /**
  • 33. * Returns the total number of collisions of this ZipCodeList object * @return the totalNumOfCollisions */ publicint getTotalNumOfCollisions(){ return totalNumOfCollisions; } /** * Returns the total number of persons injured of this ZipCo deList object * @return the totalNumOfPersonsInjured */ publicint getTotalNumOfPersonsInjured(){ return totalNumOfPersonsInjured; } /** * Returns the total number of persons killed of this ZipCode List object * @return the totalNumOfPersonsKilled */ publicint getTotalNumOfPersonsKilled(){ return totalNumOfPersonsKilled; } /** * Returns the total number of cyclists injured of this ZipCo deList object * @return the totalNumOfCyclistsInjured */ publicint getTotalNumOfCyclistsInjured(){ return totalNumOfCyclistsInjured; } /**
  • 34. * Returns the total number of cyclists killed of this ZipCode List object * @return the totalNumOfCyclistsKilled */ publicint getTotalNumOfCyclistsKilled(){ return totalNumOfCyclistsKilled; } /** * Returns the total number of pedestrians injured of this Zip CodeList object * @return the totalNumOfPedestriansInjured */ publicint getTotalNumOfPedestriansInjured(){ return totalNumOfPedestriansInjured; } /** * Returns the total number of pedestrians killed of this ZipC odeList object * @return the totalNumOfPedestriansKilled */ publicint getTotalNumOfPedestriansKilled(){ return totalNumOfPedestriansKilled; } /** * Returns the total number of motorists injured of this ZipC odeList object * @return the totalNumOfMotoristsInjured */ publicint getTotalNumOfMotoristsInjured(){ return totalNumOfMotoristsInjured; } /**
  • 35. * Returns the total number of motorists killed of this ZipCo deList object * @return the totalNumOfMotoristsKilled */ publicint getTotalNumOfMotoristsKilled(){ return totalNumOfMotoristsKilled; } /** * Computes and returns a string representation of this ZipCo deList object. * @see java.lang.Object#toString() */ @Override publicString toString(){ return"ZipCodeList for "+ zip +": "+ totalNumOfCollisions +", "+ totalNumOfPersonsInjured +", " + totalNumOfPersonsKilled +", "+ totalNumOfCyclistsInjured + ", "+ totalNumOfCyclistsKilled +", " + totalNumOfPedestriansInjured +", "+ totalNumOfPedestrians Killed +", "+ totalNumOfMotoristsInjured +", "+ totalNumOfMotoristsKilled ; } } CSCI-UA 102 sec 3,5, Fall 2015 Programming Project 6 Joanna Klukowska [email protected] Programming Project 6:
  • 36. NYPD Motor Vehicle Collisions Analysis - Revisited Due date: Dec. 11, 11:55 PM EST. You may discuss any of the assignments with your classmates and tutors (or anyone else) but all work for all assignments must be entirely your own. Any sharing or copying of assignments will be considered cheating. If you get significant help from anyone, you should acknowledge it in your submission (and your grade will be proportional to the part that you completed on your own). You are responsible for every line in your program: you need to know what it does and why. You should not use any data structures or features of Java that have not been covered in class (or the prerequisite class). If you have doubts whether or not you are allowed to use certain structures, just ask your instructor. In this project you will revisit your project 1 implementation of a program that used the NYPD motor vehicle collision data. A version of the solution to the original project is provided (it has been slightly modified from the specification of the original project). You should use that implementation as the basis for your project 6 solution. Please, see project 1 for the details of tasks and implementation requirements. Objectives The goal of this programming project is for you to master (or at least get practice on) the following tasks: • using/modifying existing code
  • 37. • selecting data structures appropriate for given tasks • writing Java programs The Program Input and Output You should not change this part of the implementation. There are three data sets posted on the course website that you should be using for this project. The largest of them contains all collision data for the entire NYC from July 1, 2012 till June 30, 2015 (three years total). The medium size data set contains all collision data for the entire NYC from July 1, 2013 till June 30, 2015 (two years total). Finally, the smallest data set contains all collision data for the entire NYC from July 1, 2014 till June 30, 2015 (one year total). For testing purposes, you may wish to use smaller data sets. Computational Task The posted program stores all the Collision objects in an ArrayList of ZipCodeList objects. The ZipCodeList object, in turn, stores all Collision objects from a particular zip code in an ArrayList of collisions. At this point in the semester, you should realize that this is not an optimal way of organizing the data. Your task for this project is to modify how the Collision objects are stored in memory when the program is running in order to improve the time performance of the
  • 38. program. 1 CSCI-UA 102 sec 3,5, Fall 2015 Programming Project 6 Joanna Klukowska [email protected] You do not need to provide implementation of any data structures yourself. You should use the implementations provided by Java API. You should only use the data structures that we discussed in class during this semester. Here is the list with links to Java API interfaces and classes: • linked list https://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.ht ml • stack https://docs.oracle.com/javase/8/docs/api/java/util/Stack.html • queue https://docs.oracle.com/javase/8/docs/api/java/util/Queue.html (any of the implementing classes) • (self-balancing) binary search tree http://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html • priority queue https://docs.oracle.com/javase/8/docs/api/java/util/PriorityQueu e.html
  • 39. • hashtable https://docs.oracle.com/javase/8/docs/api/java/util/Map.html (any of the implementing classes) You are not supposed to use all of the above data structures. Your task is to decide which of them could improve the time performance of the program and use those. You may wish to try several different changes. In your final program you should leave only the changes that resulted in a better time performance of the program. All other changes should be described in the written report (see below). Written Report: Performance Analysis You should write a 1-2 page report that summarizes the results of this project. Your report should include justification for why particular data structures are appropriate and others are not. You may wish to include time comparison results for different sizes of data sets that you obtain with the provided version of the code and with your modified version of the code. If you tried some of the data structures and they did not turn out to be appropriate, mention that in your report. If you decide to include graphs and tables, those do not count towards the 2-page limit. Program Design You should only change parts of the design of this program that
  • 40. are related to change in data structures. Overall program design should remain the same. Programming Rules You should follow the rules outlined in the document Code conventions posted on the course website at http://cs.nyu.edu/ ˜joannakl/cs102_f15/notes/CodeConventions.pdf. You must document all your code using Javadoc. Your class documentation needs to provide a description of what it is used for and the name of its author. Your methods need to have description, specification of parameters, return values, exceptions thrown and any assumptions that they are making. A class’s data fields and methods should not be declared static unless they are to be shared by all instances of the class or provide access to such data. You must use the provided implementation of the program and modify only the parts that change the storage of Collision objects. Grading Make sure that you are following all the rules in the Programming Rules section above. If your program does not compile or crashes (almost) every time it is ran, you will get a zero on the assignment. 2
  • 41. https://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.ht ml https://docs.oracle.com/javase/8/docs/api/java/util/Stack.html https://docs.oracle.com/javase/8/docs/api/java/util/Queue.html http://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html https://docs.oracle.com/javase/8/docs/api/java/util/PriorityQueu e.html https://docs.oracle.com/javase/8/docs/api/java/util/Map.html http://cs.nyu.edu/~joannakl/cs102_f15/notes/CodeConventions.p df http://cs.nyu.edu/~joannakl/cs102_f15/notes/CodeConventions.p df CSCI-UA 102 sec 3,5, Fall 2015 Programming Project 6 Joanna Klukowska [email protected] If the program does not adhere to the specification, the grade will be low and will depend on how easy it is to figure out what the program is doing. 30 points choice and use of data structures, 40 points written report with analysis of the observations, 10 points use of existing program structure, 20 points proper documentation and program style (for the parts of the code that you modify; you should add your name as the author for the classes that you modify).
  • 42. How and What to Submit Your should submit all your source code files (the ones with .java extensions only) and your report (in PDF format) in a single zip file to NYU Classes. If you are unsure how to create a zip file or how to get to your source code files, you should ask long before the project is due. If you wish to use your (one and only) freebie for this project (one week extension, no questions asked), then complete the form at http://goo.gl/forms/YFDVBlscEB before the due date for the assignment. All freebies are due seven days after the original due date and should be submitted to NYU Classes. 3 http://goo.gl/forms/YFDVBlscEB