Interactive crime statistics

Interactive crime statistics 

Assignment 1

Final Project

Design a Java application that will read a file containing data related to the US. Crime statistics from 1994-2013. The description of the file is at the end of this file. The application should provide statistical results on the data including:

  1. Population growth in percentages from each consecutive year (e.g. 1994-1995 calculation is ((262803276 – 260327021)/260327021)*100 = 0.9512%, 1995-1996 would be ((265228572 – 262803276)/262803276)*100 = 0.9229%)
  2. Years where the maximum and minimum Murder rates occurred.
  3. Years where the maximum and minimum Robbery rates occurred.

The following are some design criteria and specific requirements that need to be addressed:

  1. Use command line arguments to send in the name of the US Crime Data file.
  2. You should also use Java classes to their full extent to include multiple methods and at least two classes
  3. You are not allowed to modify the Crime.csv Statistic data file included in this assignment.
  4. Use arrays and Java classes to store the data.
  5. You should create separate methods for each of the required functionality. (e.g. getMaxMurderYear() will return the Year where the Murder rate was highest. )
  6. A user-friendly and well-organized menu should be used for users to select which data to return. A sample menu is shown in run example. You are free to enhance your design and you should add additional menu items and functionality.
  7. The menu system should be displayed at the command prompt, and continue to redisplay after results are returned or until Q is selected. If a user enters an invalid menu item, the system should redisplay the menu with a prompt asking them to enter a valid menu selection
  8. The application should keep track of the elapsed time (in seconds) between once the application starts and when the user quits the program. After the program is exited, the application should provide a prompt thanking the user for trying the US Crime Statistics program and providing the total time elapsed.
  9. When reading the Crimes file, read one line at a time and then within the loop parse each line into the USCrimeClass fields and then store that USCrimeClass Object into an array. Note you can use String.split(“,”) to split the CSV line into a the fields for setting the USCrimeClass Object.

Here is sample run:

javaTestUSCrime Crime.csv

********** Welcome to the US Crime Statistical Application **************************

Enter the number of the question you want answered. Enter ‘Q’ to quit the program :

  1. What were the percentages in population growth for each consecutive year from 1994 – 2013?
  2. What year was the Murder rate the highest?
  3. What year was the Murder rate the lowest?
  4. What year was the Robbery rate the highest?
  5. What year was the Robbery rate the lowest?
  1. Quit the program

Enter your selection: 2

The Murder rate was highest in 1994

Enter the number of the question you want answered. Enter ‘Q’ to quit the program :

  1. What were the percentages in population growth for each consecutive year from 1994 – 2013?
  2. What year was the Murder rate the highest?
  3. What year was the Murder rate the lowest?
  4. What year was the Robbery rate the highest?
  5. What year was the Robbery rate the lowest?
  1. Quit the program

Enter your selection: 5

The Robbery rate was lowest in 2013

Enter the number of the question you want answered. Enter ‘Q’ to quit the program :

  1. What were the percentages in population growth for each consecutive year from 1994 – 2013?
  2. What year was the Murder rate the highest?
  3. What year was the Murder rate the lowest?
  4. What year was the Robbery rate the highest?
  5. What year was the Robbery rate the lowest?
  1. Quit the program

Enter your selection: Q

Thank you for trying the US Crimes Statistics Program.

Elapsed time in seconds was: 32

Specifically, the following style guide attributes should be addressed:

 Header comments include filename, author, date and brief purpose of the program.

 In-line comments used to describe major functionality of the code.

 Meaningful variable names and prompts applied.

 Class names are written in UpperCamelCase.

 Variable names are written in lowerCamelCase.

 Constant names are in written in All Capitals.

 Braces use K&R style. 

Solution

Crime 

Year Population Murder rate Robbery rate
1994 260327021 9 237.8
1995 262803276 8.2 220.9
1996 265228572 7.4 201.9
1997 267783607 6.8 186.2
1998 270248003 6.3 165.5
1999 272690813 5.7 150.1
2000 281421906 5.5 145
20013 285317559 5.6 148.5
2002 287973924 5.6 146.1
2003 290788976 5.7 142.5
2004 293656842 5.5 136.7
2005 296507061 5.6 140.8
2006 299398484 5.8 150
2007 301621157 5.7 148.3
2008 304059724 5.4 145.9
2009 307006550 5 133.1
2010 309330219 4.8 119.3
2011 311587816 4.7 113.9
20124 313873685 4.7 113.1
2013 316128839 4.5 109.1

Crimes.java

importjava.io.BufferedReader;

importjava.io.FileInputStream;

importjava.io.IOException;

importjava.io.InputStreamReader;

importjava.util.ArrayList;

public class Crimes {

//field to store all the data coming from the file

privateArrayList<USCrime> data;

/*

* @constructor to fill the attribute with the data on the file

*/

public Crimes(String fileName){

//initialize data

data = new ArrayList<USCrime>();

//stream reader to read information from the csv file

InputStreamReaderisr;

try {

isr = new InputStreamReader(new FileInputStream(fileName));

BufferedReader in = new BufferedReader(isr);

//we call the method responsible of reading the data and parsing and storing it in data

initiateData(in);

in.close();

} catch (Exception e) {

e.printStackTrace();

}

}

/*

* @paramBufferReader from the file containing the data

* @throws IOException if

*/

private void initiateData(BufferedReader in) throws IOException {

//a string to store each line of the file

String line;

//we skip the first line because it doesn’t contain data

in.readLine();

//we iterate over the lines of the file while we didn’t get to the end of it

while((line=in.readLine())!=null){

//we parse the line to a USCrime object

USCrimeusCrime = parseUSCrime(line);

data.add(usCrime);

}

}

privateUSCrimeparseUSCrime(String line) {

String[] lineParts = line.split(“,”);

int year = Integer.parseInt(lineParts[0]);

int population = Integer.parseInt(lineParts[1]);

floatmurderRate = Float.parseFloat(lineParts[2]);

floatrobberyRate = Float.parseFloat(lineParts[3]);

return new USCrime(year, population, murderRate, robberyRate);

}

publicintgetYearWithHighestMurder() {

inthighestYear = data.get(0).getYear();

float max = data.get(0).getMurderRate();

for(USCrime crime : data){

floatcurrentRate = crime.getMurderRate();

if(currentRate>max){

highestYear = crime.getYear();

max = currentRate;

}

}

returnhighestYear;

}

publicintgetYearWithLowestMurder() {

intlowestYear = data.get(0).getYear();

float min = data.get(0).getMurderRate();

for(USCrime crime : data){

floatcurrentRate = crime.getMurderRate();

if(currentRate<min){

lowestYear = crime.getYear();

min = currentRate;

}

}

returnlowestYear;

}

publicintgetYearWithHighestRobery() {

inthighestYear = data.get(0).getYear();

float max = data.get(0).getRobberyRate();

for(USCrime crime : data){

floatcurrentRate = crime.getRobberyRate();

if(currentRate>max){

highestYear = crime.getYear();

max = currentRate;

}

}

returnhighestYear;

}

publicintgetYearWithLowestRobery() {

intlowestYear = data.get(0).getYear();

float min = data.get(0).getRobberyRate();

for(USCrime crime : data){

floatcurrentRate = crime.getRobberyRate();

if(currentRate<min){

lowestYear = crime.getYear();

min = currentRate;

}

}

returnlowestYear;

}

public double[] getPopulationGrowth() {

doublegrouths[] = new double[data.size()-1];

for(int i=0;i<data.size()-2;i++){

intactualPopulation = data.get(i).getPopulation();

intnextPopulation = data.get(i+1).getPopulation();

double growth = (double)(nextPopulation-actualPopulation)/actualPopulation;

grouths[i] = 100*growth;

}

returngrouths;

}

publicintgetFirstYear() {

returndata.get(0).getYear();

}

}

TestUSCrime.java

importjava.util.Scanner;

public class TestUSCrime {

private static long elapsedTime;

public static void main(String[] args) {

//seting the start time

longstartTime = System.currentTimeMillis();

//variable to store the end time

longendTime;

//scanner to read user input

Scanner input = new Scanner(System.in);

//Our crimes class to do the calculation

Crimes crimes = new Crimes(args[0]);

//we print the welcome message

printWelcomeMessage();

//a character to store the request of the user

charreq;

do{

//every time we iterate we ask the user what he wants

printRequestMessage();

//we store the character entred by the user

req = input.next().charAt(0);

//to store the result of the calculation

int result ;

//depending on the request of the client we choose the action to do

switch(req){

case ‘1’ :

double[] pourcentages = crimes.getPopulationGrowth();

for(int i=0;i<pourcentages.length;i++){

int from = crimes.getFirstYear()+i;

int to = from+1;

System.out.printf(“Population growth pourcentage from “+from+” to “+to+ ” is : %.4f”,pourcentages[i]);

System.out.println(“%”);

}

break;

case ‘2’ :

result = crimes.getYearWithHighestMurder();

System.out.println(“The Murder rate was highest in “+result);

break;

case ‘3’:

result = crimes.getYearWithLowestMurder();

System.out.println(“The Murder rate was lowest in “+result);

break;

case ‘4’ :

result = crimes.getYearWithHighestRobery();

System.out.println(“The Robbery rate was highest in “+result);

break;

case ‘5’ :

result = crimes.getYearWithLowestRobery();

System.out.println(“The Robbery rate was lowest in “+result);

break;

case ‘Q’ :

break;

}

}while(req!=’Q’);

input.close();

endTime = System.currentTimeMillis();

elapsedTime = (endTime – startTime)/1000;

printExitMessage();

}

private static void printWelcomeMessage() {

System.out.println(“********** Welcome to the US Crime Statistical Application **************************”);

}

private static void printRequestMessage() {

System.out.println(“Enter the number of the question you want answered. Enter ‘Q’ to quit the program :”);

System.out.println(“1.  What were the percentages in population growth for each consecutive year from 1994 – 2013?”);

System.out.println(“2.  What year was the Murder rate the highest?”);

System.out.println(“3.  What year was the Murder rate the lowest?”);

System.out.println(“4.  What year was the Robbery rate the highest?”);

System.out.println(“5.  What year was the Robbery rate the lowest?”);

System.out.println(“Q.    Quit the program”);

}

private static void printExitMessage() {

System.out.println(“Thank you for trying the US Crimes Statistics Program.”);

System.out.println(“Elapsed time in seconds was: “+ elapsedTime);

}

}

USCrime.java

public class USCrime {

privateint year;

privateint population;

private float murderRate;

private float robberyRate;

publicUSCrime(int year, int population, float murderRate, float robberyRate) {

this.year = year;

this.population = population;

this.murderRate = murderRate;

this.robberyRate = robberyRate;

}

publicintgetYear() {

return year;

}

public void setYear(int year) {

this.year = year;

}

publicintgetPopulation() {

return population;

}

public void setPopulation(int population) {

this.population = population;

}

public float getMurderRate() {

returnmurderRate;

}

public void setMurderRate(float murderRate) {

this.murderRate = murderRate;

}

public float getRobberyRate() {

returnrobberyRate;

}

public void setRobberyRate(float robberyRate) {

this.robberyRate = robberyRate;

}

}

Assignment 2

Write a Java program the displays the State bird and flower. You should also use Java classes to their full extent to include multiple methods and at least two classes. The program should prompt the user to enter a State and print both the State bird and flower. The user should be able to enter a State without worrying about case. (e.g. Users could enter Maryland, maryland, MARYLAND or any other possible combination of lower and upper case characters. States may also contain leading and trailing white spaces. Hint: Store the State information in a multi-dimensional array. The program should continue to prompt the user to enter a state until “None” is entered. After all States have been entered by the user, the program should display a summary of the results. You will need to do some research to find the State birds and flowers. Here is a sample run:

Enter a State or None to exit: Maryland Bird: Baltimore Oriole Flower: Black-eyed Susan Enter a State or None to exit: Delaware Bird: Blue Hen Chicken Flower: Peach Blossom Enter a State or None to exit: None

**** Thank you ***** A summary report for each State, Bird, and Flower is: Maryland, Baltimore Oriole, Black-eyed Susan Delaware, Blue Hen Chicken, Peach Blossom Please visit our site again!

Create a test class that constructs at least 3 States objects. For each of the objects constructed, demonstrate the use of each of the methods.

Specifically, the following style guide attributes should be addressed:

 Header comments include filename, author, date and brief purpose of the program.

 In-line comments used to describe major functionality of the code.

 Meaningful variable names and prompts applied.

 Class names are written in UpperCamelCase.

 Variable names are written in lowerCamelCase.

 Constant names are in written in All Capitals.

 Braces use K&R style.

Solution 

Test cases :

  Input expected actual Pass/fail
Test case 1 NEW YORK Bird : Bluebird

Flower : Rose

Bird : Bluebird

Flower : Rose

pass
Test case 2 AlaBaMa Bird : Yellowhammer

Flower : Camellia

Bird : Yellowhammer

Flower : Camellia

pass
Test case 3 None **** Thank you *****

A summary report for each State, Bird, and Flower is:

Alabama, Yellowhammer, Camellia

New York, Bluebird, Rose

Please visit our site again!

**** Thank you *****

A summary report for each State, Bird, and Flower is:

Alabama, Yellowhammer, Camellia

New York, Bluebird, Rose

Please visit our site again!

pass

screenshot :

StateEntity.java 

/*

*  @Description : this class represents our states data with getters and setters

*/

public class StateEntity {

private String stateName;

private String bird;

private String flower;

publicStateEntity(String stateName, String bird, String flower) {

this.stateName = stateName;

this.bird = bird;

this.flower = flower;

}

/**

* @return the stateName

*/

public String getStateName() {

returnstateName;

}

/**

* @paramstateName the stateName to set

*/

public void setStateName(String stateName) {

this.stateName = stateName;

}

/**

* @return the bird

*/

public String getBird() {

return bird;

}

/**

* @param bird the bird to set

*/

public void setBird(String bird) {

this.bird = bird;

}

/**

* @return the flower

*/

public String getFlower() {

return flower;

}

/**

* @param flower the flower to set

*/

public void setFlower(String flower) {

this.flower = flower;

}

}

StatesDataEntry.java 

importjava.util.ArrayList;

importjava.util.HashSet;

importjava.util.Iterator;

importjava.util.Scanner;

importjava.util.Set;

/*

*  @Description : this class is the main class of the program , it prompts the user

*  to enter a state and it prints the bird and the flower

*/

public class StatesDataEntry {

//this list will contain the data we will work with that represents the states

//and the bird and the flower of each one

private static ArrayList<StateEntity>statesData;

//the method that will have the responsibility to initialize the statesData

public static void initData() {

statesData = new ArrayList<StateEntity>();

statesData.add(new StateEntity(“Alabama”, “Yellowhammer”, “Camellia”));

statesData.add(new StateEntity(“Alaska”, ” Willow Ptarmigan”, “Forget-me-not”));

statesData.add(new StateEntity(“Arizona”, “Cactus Wren”, “Saguaro Cactus Blossom”));

statesData.add(new StateEntity(“California”, ”  California Valley Quail”, ”  Golden Poppy”));

statesData.add(new StateEntity(“Florida”, “Mockingbird”, “Orange Blossom”));

statesData.add(new StateEntity(“Maryland”, “Baltimore Oriole”, “Black-Eyed Susan”));

statesData.add(new StateEntity(“Delaware”, “Blue Hen Chicken”, “Peach Blossom”));

statesData.add(new StateEntity(“Massachusetts”, “Chickadee”, “Mayflower”));

statesData.add(new StateEntity(“New Jersey”, “Eastern Goldfinch”, “Purple Violet”));

statesData.add(new StateEntity(“New York”, “Bluebird”, “Rose”));

statesData.add(new StateEntity(“North Carolina”, ”   Cardinal”, “Dogwood”));

statesData.add(new StateEntity(“South Carolina”, “Carolina Wren”, “Yellow Jessamine”));

statesData.add(new StateEntity(“Washington”, “Willow Goldfinch”, “Western Rhododendron”));

}

public static void main(String[] args){

initData();

Set<StateEntity>requestsHistory = new HashSet<StateEntity>();

Scanner input = new Scanner(System.in);

String request = propmtUser(input);

do{

StateEntity state = searchFor(request);

if(state!=null){

printResult(state);

requestsHistory.add(state);

}

request = propmtUser(input);

}while(!request.equals(“None”));

printSummary(requestsHistory);

}

/*

* method to print the summary

*/

private static void printSummary(Set<StateEntity>requestsHistory) {

System.out.println(“**** Thank you *****”);

System.out.println(“A summary report for each State, Bird, and Flower is:”);

Iterator<StateEntity> iterator = requestsHistory.iterator();

while(iterator.hasNext()){

StateEntity current = iterator.next();

System.out.println(current.getStateName()+”, “+current.getBird()+”, “+current.getFlower());

}

System.out.println(“Please visit our site again!”);

}

/*

* method to print the results

* @param the state the print

*/

private static void printResult(StateEntity state) {

System.out.println(“Bird : “+state.getBird());

System.out.println(“Flower : “+state.getFlower());

}

/*

* method to prompt the user

* @param the scanner for reading the input

* @return the string entred by the user

*/

private static String propmtUser(Scanner input) {

System.out.println(“Enter a State or None to exit:”);

String request = input.nextLine();

return request;

}

/*

* method to search for a state in the data based on the name

* @paramrequest : state name to look for

* @return the state if it’s found

*/

private static StateEntitysearchFor(String request) {

for(StateEntity se : statesData){

//transform the request and the state name in lower case to avoid case sensitive

String requestLow = request.toLowerCase();

String stateLow = se.getStateName().toLowerCase();

//if they are the same , return the state

if(stateLow.equals(requestLow))

return se;

}

//if we didn’t find anything , return null

return null;

}

}

Test.java 

import static org.junit.Assert.*;

public class Test {

@org.junit.Test

public void testAlabama() {

StateEntityalabama = new StateEntity(“Alabama”, “Yellowhammer”, “Camellia”);

assertEquals(“Alabama”, alabama.getStateName());

assertEquals(“Yellowhammer”, alabama.getBird());

assertEquals(“Camellia”, alabama.getFlower());

alabama.setStateName(“ALABAMA”);

assertEquals(“ALABAMA”, alabama.getStateName());

alabama.setBird(“YH”);

assertEquals(“YH”, alabama.getBird());

alabama.setFlower(“C”);

assertEquals(“C”, alabama.getFlower());

}

@org.junit.Test

public void testNY() {

StateEntityny = new StateEntity(“New York”, “Bluebird”, “Rose”);

assertEquals(“New York”, ny.getStateName());

assertEquals(“Bluebird”, ny.getBird());

assertEquals(“Rose”, ny.getFlower());

ny.setStateName(“NY State”);

assertEquals(“NY State”, ny.getStateName());

ny.setBird(“BB”);

assertEquals(“BB”, ny.getBird());

ny.setFlower(“R”);

assertEquals(“R”, ny.getFlower());

}

@org.junit.Test

public void testSC() {

StateEntitysouthCarolina = new StateEntity(“South Carolina”, “Carolina Wren”, “Yellow Jessamine”);

assertEquals(“South Carolina”, southCarolina.getStateName());

assertEquals(“Carolina Wren”, southCarolina.getBird());

assertEquals(“Yellow Jessamine”, southCarolina.getFlower());

southCarolina.setStateName(“SC State”);

assertEquals(“SC State”, southCarolina.getStateName());

southCarolina.setBird(“CW”);

assertEquals(“CW”, southCarolina.getBird());

southCarolina.setFlower(“YJ”);

assertEquals(“YJ”, southCarolina.getFlower());

}

}