SlideShare a Scribd company logo
1 of 43
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
The topic you are going to write about is The Cultural
Miscommunication / Cultural Expectations / Culture Shock
Its one topic but devid to 3 part
We have to have to start with Introduction and end with
conclusion and the important is the thesestament
1- MLA
2- from the topic I choose to write about I need you to research
some sources that support and substantiate ur ideas.
3- Your basic thesis will involve the following : What topics
have impressed u most? Which would like to learn more about?
Can we, as world citizens, solve some of the challenges that
impact our society so strongly in these times ? If so, how?
4- 3-5 pages long ( not counting title or refrences pages )
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 2015Programming Project 6Joann.docx

More Related Content

Similar to CSCI-UA 102 sec 3,5, Fall 2015Programming Project 6Joann.docx

Software design.edited (1)
Software design.edited (1)Software design.edited (1)
Software design.edited (1)FarjanaAhmed3
 
Write and run three interesting queries/tutorialoutlet
Write and run three interesting queries/tutorialoutletWrite and run three interesting queries/tutorialoutlet
Write and run three interesting queries/tutorialoutletTitmuss
 
Week 4 Assignment - Software Development PlanScenario-Your team has be.docx
Week 4 Assignment - Software Development PlanScenario-Your team has be.docxWeek 4 Assignment - Software Development PlanScenario-Your team has be.docx
Week 4 Assignment - Software Development PlanScenario-Your team has be.docxestefana2345678
 
1 Project 2 Introduction - the SeaPort Project seri.docx
1  Project 2 Introduction - the SeaPort Project seri.docx1  Project 2 Introduction - the SeaPort Project seri.docx
1 Project 2 Introduction - the SeaPort Project seri.docxhoney725342
 
Debug and Fix If Statements In this assessment, you will d.docx
Debug and Fix If Statements In this assessment, you will d.docxDebug and Fix If Statements In this assessment, you will d.docx
Debug and Fix If Statements In this assessment, you will d.docxedwardmarivel
 
Runtime Behavior of JavaScript Programs
Runtime Behavior of JavaScript ProgramsRuntime Behavior of JavaScript Programs
Runtime Behavior of JavaScript ProgramsIRJET Journal
 
Introduction to object oriented language
Introduction to object oriented languageIntroduction to object oriented language
Introduction to object oriented languagefarhan amjad
 
Basic iOS Training with SWIFT - Part 1
Basic iOS Training with SWIFT - Part 1Basic iOS Training with SWIFT - Part 1
Basic iOS Training with SWIFT - Part 1Manoj Ellappan
 
The 2014 Decision Makers Guide to Java Web Frameworks
The 2014 Decision Makers Guide to Java Web FrameworksThe 2014 Decision Makers Guide to Java Web Frameworks
The 2014 Decision Makers Guide to Java Web FrameworksKunal Ashar
 
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosUnit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosFlutter Agency
 
CSCI-383 Lecture 5-6-7: Object-Oriented Design
CSCI-383 Lecture 5-6-7: Object-Oriented DesignCSCI-383 Lecture 5-6-7: Object-Oriented Design
CSCI-383 Lecture 5-6-7: Object-Oriented DesignJI Ruan
 
InstructionsFor this discussion, you will need the posts. Go to
InstructionsFor this discussion, you will need the posts. Go to InstructionsFor this discussion, you will need the posts. Go to
InstructionsFor this discussion, you will need the posts. Go to TatianaMajor22
 
Phase 2 - Task 1Task TypeDiscussion BoardDeliverable Length.docx
Phase 2 - Task 1Task TypeDiscussion BoardDeliverable Length.docxPhase 2 - Task 1Task TypeDiscussion BoardDeliverable Length.docx
Phase 2 - Task 1Task TypeDiscussion BoardDeliverable Length.docxrandymartin91030
 

Similar to CSCI-UA 102 sec 3,5, Fall 2015Programming Project 6Joann.docx (19)

Software design.edited (1)
Software design.edited (1)Software design.edited (1)
Software design.edited (1)
 
Write and run three interesting queries/tutorialoutlet
Write and run three interesting queries/tutorialoutletWrite and run three interesting queries/tutorialoutlet
Write and run three interesting queries/tutorialoutlet
 
Week 4 Assignment - Software Development PlanScenario-Your team has be.docx
Week 4 Assignment - Software Development PlanScenario-Your team has be.docxWeek 4 Assignment - Software Development PlanScenario-Your team has be.docx
Week 4 Assignment - Software Development PlanScenario-Your team has be.docx
 
1 Project 2 Introduction - the SeaPort Project seri.docx
1  Project 2 Introduction - the SeaPort Project seri.docx1  Project 2 Introduction - the SeaPort Project seri.docx
1 Project 2 Introduction - the SeaPort Project seri.docx
 
Debug and Fix If Statements In this assessment, you will d.docx
Debug and Fix If Statements In this assessment, you will d.docxDebug and Fix If Statements In this assessment, you will d.docx
Debug and Fix If Statements In this assessment, you will d.docx
 
Runtime Behavior of JavaScript Programs
Runtime Behavior of JavaScript ProgramsRuntime Behavior of JavaScript Programs
Runtime Behavior of JavaScript Programs
 
Introduction to object oriented language
Introduction to object oriented languageIntroduction to object oriented language
Introduction to object oriented language
 
FinalReport
FinalReportFinalReport
FinalReport
 
SE.pdf
SE.pdfSE.pdf
SE.pdf
 
Basic iOS Training with SWIFT - Part 1
Basic iOS Training with SWIFT - Part 1Basic iOS Training with SWIFT - Part 1
Basic iOS Training with SWIFT - Part 1
 
Sdlc
SdlcSdlc
Sdlc
 
Sdlc
SdlcSdlc
Sdlc
 
Jagrat_Mankad
Jagrat_MankadJagrat_Mankad
Jagrat_Mankad
 
The 2014 Decision Makers Guide to Java Web Frameworks
The 2014 Decision Makers Guide to Java Web FrameworksThe 2014 Decision Makers Guide to Java Web Frameworks
The 2014 Decision Makers Guide to Java Web Frameworks
 
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosUnit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
 
CSCI-383 Lecture 5-6-7: Object-Oriented Design
CSCI-383 Lecture 5-6-7: Object-Oriented DesignCSCI-383 Lecture 5-6-7: Object-Oriented Design
CSCI-383 Lecture 5-6-7: Object-Oriented Design
 
InstructionsFor this discussion, you will need the posts. Go to
InstructionsFor this discussion, you will need the posts. Go to InstructionsFor this discussion, you will need the posts. Go to
InstructionsFor this discussion, you will need the posts. Go to
 
Control term proj3012
Control term proj3012Control term proj3012
Control term proj3012
 
Phase 2 - Task 1Task TypeDiscussion BoardDeliverable Length.docx
Phase 2 - Task 1Task TypeDiscussion BoardDeliverable Length.docxPhase 2 - Task 1Task TypeDiscussion BoardDeliverable Length.docx
Phase 2 - Task 1Task TypeDiscussion BoardDeliverable Length.docx
 

More from faithxdunce63732

Assignment DetailsScenario You are member of a prisoner revie.docx
Assignment DetailsScenario You are member of a prisoner revie.docxAssignment DetailsScenario You are member of a prisoner revie.docx
Assignment DetailsScenario You are member of a prisoner revie.docxfaithxdunce63732
 
Assignment DetailsScenario You are an investigator for Child .docx
Assignment DetailsScenario You are an investigator for Child .docxAssignment DetailsScenario You are an investigator for Child .docx
Assignment DetailsScenario You are an investigator for Child .docxfaithxdunce63732
 
Assignment DetailsScenario You are a new patrol officer in a .docx
Assignment DetailsScenario You are a new patrol officer in a .docxAssignment DetailsScenario You are a new patrol officer in a .docx
Assignment DetailsScenario You are a new patrol officer in a .docxfaithxdunce63732
 
Assignment DetailsScenario Generally, we have considered sexual.docx
Assignment DetailsScenario Generally, we have considered sexual.docxAssignment DetailsScenario Generally, we have considered sexual.docx
Assignment DetailsScenario Generally, we have considered sexual.docxfaithxdunce63732
 
Assignment DetailsPower’s on, Power’s Off!How convenient is.docx
Assignment DetailsPower’s on, Power’s Off!How convenient is.docxAssignment DetailsPower’s on, Power’s Off!How convenient is.docx
Assignment DetailsPower’s on, Power’s Off!How convenient is.docxfaithxdunce63732
 
Assignment DetailsIn 1908, playwright Israel Zangwill referred to .docx
Assignment DetailsIn 1908, playwright Israel Zangwill referred to .docxAssignment DetailsIn 1908, playwright Israel Zangwill referred to .docx
Assignment DetailsIn 1908, playwright Israel Zangwill referred to .docxfaithxdunce63732
 
Assignment DetailsPart IRespond to the following.docx
Assignment DetailsPart IRespond to the following.docxAssignment DetailsPart IRespond to the following.docx
Assignment DetailsPart IRespond to the following.docxfaithxdunce63732
 
Assignment DetailsPlease discuss the following in your main post.docx
Assignment DetailsPlease discuss the following in your main post.docxAssignment DetailsPlease discuss the following in your main post.docx
Assignment DetailsPlease discuss the following in your main post.docxfaithxdunce63732
 
Assignment DetailsPennsylvania was the leader in sentencing and .docx
Assignment DetailsPennsylvania was the leader in sentencing and .docxAssignment DetailsPennsylvania was the leader in sentencing and .docx
Assignment DetailsPennsylvania was the leader in sentencing and .docxfaithxdunce63732
 
Assignment DetailsPart IRespond to the followingReview .docx
Assignment DetailsPart IRespond to the followingReview .docxAssignment DetailsPart IRespond to the followingReview .docx
Assignment DetailsPart IRespond to the followingReview .docxfaithxdunce63732
 
Assignment DetailsPart IRespond to the following questio.docx
Assignment DetailsPart IRespond to the following questio.docxAssignment DetailsPart IRespond to the following questio.docx
Assignment DetailsPart IRespond to the following questio.docxfaithxdunce63732
 
Assignment DetailsPart IRespond to the following questions.docx
Assignment DetailsPart IRespond to the following questions.docxAssignment DetailsPart IRespond to the following questions.docx
Assignment DetailsPart IRespond to the following questions.docxfaithxdunce63732
 
Assignment DetailsOne thing that unites all humans—despite cultu.docx
Assignment DetailsOne thing that unites all humans—despite cultu.docxAssignment DetailsOne thing that unites all humans—despite cultu.docx
Assignment DetailsOne thing that unites all humans—despite cultu.docxfaithxdunce63732
 
Assignment DetailsMN551Develop cooperative relationships with.docx
Assignment DetailsMN551Develop cooperative relationships with.docxAssignment DetailsMN551Develop cooperative relationships with.docx
Assignment DetailsMN551Develop cooperative relationships with.docxfaithxdunce63732
 
Assignment DetailsInfluence ProcessesYou have been encourag.docx
Assignment DetailsInfluence ProcessesYou have been encourag.docxAssignment DetailsInfluence ProcessesYou have been encourag.docx
Assignment DetailsInfluence ProcessesYou have been encourag.docxfaithxdunce63732
 
Assignment DetailsIn this assignment, you will identify and .docx
Assignment DetailsIn this assignment, you will identify and .docxAssignment DetailsIn this assignment, you will identify and .docx
Assignment DetailsIn this assignment, you will identify and .docxfaithxdunce63732
 
Assignment DetailsFinancial statements are the primary means of .docx
Assignment DetailsFinancial statements are the primary means of .docxAssignment DetailsFinancial statements are the primary means of .docx
Assignment DetailsFinancial statements are the primary means of .docxfaithxdunce63732
 
Assignment DetailsIn this assignment, you will identify a pr.docx
Assignment DetailsIn this assignment, you will identify a pr.docxAssignment DetailsIn this assignment, you will identify a pr.docx
Assignment DetailsIn this assignment, you will identify a pr.docxfaithxdunce63732
 
Assignment DetailsHealth information technology (health IT) .docx
Assignment DetailsHealth information technology (health IT) .docxAssignment DetailsHealth information technology (health IT) .docx
Assignment DetailsHealth information technology (health IT) .docxfaithxdunce63732
 
Assignment DetailsDiscuss the followingWhat were some of .docx
Assignment DetailsDiscuss the followingWhat were some of .docxAssignment DetailsDiscuss the followingWhat were some of .docx
Assignment DetailsDiscuss the followingWhat were some of .docxfaithxdunce63732
 

More from faithxdunce63732 (20)

Assignment DetailsScenario You are member of a prisoner revie.docx
Assignment DetailsScenario You are member of a prisoner revie.docxAssignment DetailsScenario You are member of a prisoner revie.docx
Assignment DetailsScenario You are member of a prisoner revie.docx
 
Assignment DetailsScenario You are an investigator for Child .docx
Assignment DetailsScenario You are an investigator for Child .docxAssignment DetailsScenario You are an investigator for Child .docx
Assignment DetailsScenario You are an investigator for Child .docx
 
Assignment DetailsScenario You are a new patrol officer in a .docx
Assignment DetailsScenario You are a new patrol officer in a .docxAssignment DetailsScenario You are a new patrol officer in a .docx
Assignment DetailsScenario You are a new patrol officer in a .docx
 
Assignment DetailsScenario Generally, we have considered sexual.docx
Assignment DetailsScenario Generally, we have considered sexual.docxAssignment DetailsScenario Generally, we have considered sexual.docx
Assignment DetailsScenario Generally, we have considered sexual.docx
 
Assignment DetailsPower’s on, Power’s Off!How convenient is.docx
Assignment DetailsPower’s on, Power’s Off!How convenient is.docxAssignment DetailsPower’s on, Power’s Off!How convenient is.docx
Assignment DetailsPower’s on, Power’s Off!How convenient is.docx
 
Assignment DetailsIn 1908, playwright Israel Zangwill referred to .docx
Assignment DetailsIn 1908, playwright Israel Zangwill referred to .docxAssignment DetailsIn 1908, playwright Israel Zangwill referred to .docx
Assignment DetailsIn 1908, playwright Israel Zangwill referred to .docx
 
Assignment DetailsPart IRespond to the following.docx
Assignment DetailsPart IRespond to the following.docxAssignment DetailsPart IRespond to the following.docx
Assignment DetailsPart IRespond to the following.docx
 
Assignment DetailsPlease discuss the following in your main post.docx
Assignment DetailsPlease discuss the following in your main post.docxAssignment DetailsPlease discuss the following in your main post.docx
Assignment DetailsPlease discuss the following in your main post.docx
 
Assignment DetailsPennsylvania was the leader in sentencing and .docx
Assignment DetailsPennsylvania was the leader in sentencing and .docxAssignment DetailsPennsylvania was the leader in sentencing and .docx
Assignment DetailsPennsylvania was the leader in sentencing and .docx
 
Assignment DetailsPart IRespond to the followingReview .docx
Assignment DetailsPart IRespond to the followingReview .docxAssignment DetailsPart IRespond to the followingReview .docx
Assignment DetailsPart IRespond to the followingReview .docx
 
Assignment DetailsPart IRespond to the following questio.docx
Assignment DetailsPart IRespond to the following questio.docxAssignment DetailsPart IRespond to the following questio.docx
Assignment DetailsPart IRespond to the following questio.docx
 
Assignment DetailsPart IRespond to the following questions.docx
Assignment DetailsPart IRespond to the following questions.docxAssignment DetailsPart IRespond to the following questions.docx
Assignment DetailsPart IRespond to the following questions.docx
 
Assignment DetailsOne thing that unites all humans—despite cultu.docx
Assignment DetailsOne thing that unites all humans—despite cultu.docxAssignment DetailsOne thing that unites all humans—despite cultu.docx
Assignment DetailsOne thing that unites all humans—despite cultu.docx
 
Assignment DetailsMN551Develop cooperative relationships with.docx
Assignment DetailsMN551Develop cooperative relationships with.docxAssignment DetailsMN551Develop cooperative relationships with.docx
Assignment DetailsMN551Develop cooperative relationships with.docx
 
Assignment DetailsInfluence ProcessesYou have been encourag.docx
Assignment DetailsInfluence ProcessesYou have been encourag.docxAssignment DetailsInfluence ProcessesYou have been encourag.docx
Assignment DetailsInfluence ProcessesYou have been encourag.docx
 
Assignment DetailsIn this assignment, you will identify and .docx
Assignment DetailsIn this assignment, you will identify and .docxAssignment DetailsIn this assignment, you will identify and .docx
Assignment DetailsIn this assignment, you will identify and .docx
 
Assignment DetailsFinancial statements are the primary means of .docx
Assignment DetailsFinancial statements are the primary means of .docxAssignment DetailsFinancial statements are the primary means of .docx
Assignment DetailsFinancial statements are the primary means of .docx
 
Assignment DetailsIn this assignment, you will identify a pr.docx
Assignment DetailsIn this assignment, you will identify a pr.docxAssignment DetailsIn this assignment, you will identify a pr.docx
Assignment DetailsIn this assignment, you will identify a pr.docx
 
Assignment DetailsHealth information technology (health IT) .docx
Assignment DetailsHealth information technology (health IT) .docxAssignment DetailsHealth information technology (health IT) .docx
Assignment DetailsHealth information technology (health IT) .docx
 
Assignment DetailsDiscuss the followingWhat were some of .docx
Assignment DetailsDiscuss the followingWhat were some of .docxAssignment DetailsDiscuss the followingWhat were some of .docx
Assignment DetailsDiscuss the followingWhat were some of .docx
 

Recently uploaded

Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 

Recently uploaded (20)

Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 

CSCI-UA 102 sec 3,5, Fall 2015Programming Project 6Joann.docx

  • 1. 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.
  • 2. 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
  • 3. 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
  • 4. • 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
  • 5. 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.
  • 6. 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,
  • 7. 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 The topic you are going to write about is The Cultural Miscommunication / Cultural Expectations / Culture Shock Its one topic but devid to 3 part We have to have to start with Introduction and end with conclusion and the important is the thesestament
  • 8. 1- MLA 2- from the topic I choose to write about I need you to research some sources that support and substantiate ur ideas. 3- Your basic thesis will involve the following : What topics have impressed u most? Which would like to learn more about? Can we, as world citizens, solve some of the challenges that impact our society so strongly in these times ? If so, how? 4- 3-5 pages long ( not counting title or refrences pages ) 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;
  • 9. 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.
  • 10. * * @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);
  • 11. } /* * 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 +"]";
  • 12. } /** * 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;
  • 13. } /** * 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; }
  • 14. /** * 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;
  • 15. } /** * 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; }
  • 16. } 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
  • 17. 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 }
  • 18. 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());
  • 19. 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
  • 20. 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; } }
  • 21. 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
  • 22. * 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); }
  • 23. 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.
  • 24. 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();
  • 25. 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();
  • 26. //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
  • 27. * @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))); }
  • 28. 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")||
  • 29. 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();
  • 30. //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.
  • 31. 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
  • 32. * 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())
  • 33. - ( 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
  • 34. 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
  • 35. * 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}
  • 36. 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
  • 37. * 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( );
  • 38. 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)
  • 39. */ @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
  • 40. * @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
  • 41. 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
  • 42. 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 ; } }