我正在尝试使其工作,但一直说您键入位置时文件找不到。.我希望用户能够放置需要读取的文件的位置。我不知道如何停止错误。任何帮助,将不胜感激。输出结果使我可以键入文件位置,但之后出现错误。
import java.util.ArrayList;
import java.util.List;
public class CrimeStatistics {
// instantiate List object - it is static since all instances will use the same data
private static List<CrimeDataObjects> recordList = new ArrayList<CrimeDataObjects>();
// constructor
public CrimeStatistics() {
}
//static block to call compile data and fill List - used in all methods
static{
CrimeDataRecords.readData();
recordList = CrimeDataRecords.getDataRecords();
}
/*
* popGrowthRate method - compiles and displays population growth year to year
*/
public ArrayList<String> popGrowthRate () {
//declare variables
String tempYears; // temporarily holds year value
double tempGrowth; //stores the growth percent
String yearToYearGrowth;
ArrayList<String> growthRateChart = new ArrayList<String>();//array to hold data from CrimeDataRecords
// add header to array
growthRateChart.add("**** Year to Year ****");
growthRateChart.add("**** Growth Rates ****");
growthRateChart.add("----------------------");
for (int i = 0; i < recordList.size()-1; i++){ // Loop through List of CrimeDataObjects
tempYears = Integer.toString(recordList.get(i).getYear()); // get year and store in variable
tempYears += " - "; // add String to variable
tempYears += Integer.toString(recordList.get(i+1).getYear()); // get next year and add to variable
tempGrowth = (((recordList.get(i+1).getPoplulation() -
recordList.get(i).getPoplulation()) /
(recordList).get(i).getPoplulation()))*100; // calculate growth and add to variable
yearToYearGrowth = String.format("%s = %.4f%%" ,tempYears, tempGrowth);// form string for year to year growth
growthRateChart.add(yearToYearGrowth); // add string to arrayList
}// end for loop
return growthRateChart;
}// end popGrowthRate method
/*
* murderRateHigh method - outputs highest year and rate
*/
public String murderRateHigh () {
// declare variables
int year = 0;
float highestRate = 0;
String murderRateHigh = "\n**** Highest Murder Rate ****" +
"\n-----------------------------\n" +
"Year: ";
year = recordList.get(0).getYear();// store year of first record
highestRate = recordList.get(0).getMurderNonNegManslaughterRate();//store rate of first record
// loop through records and compare rates
for( int i = 1; i < recordList.size(); i++ ){
if(highestRate < recordList.get(i).getMurderNonNegManslaughterRate() ){ //if rate is higher
year = recordList.get(i).getYear();// store year
highestRate = recordList.get(i).getMurderNonNegManslaughterRate();//store rate
}// end if
}// end for loop
murderRateHigh += Integer.toString(year); //add year to string
murderRateHigh += " Murder Rate:";// add title to string
murderRateHigh += Float.toString(highestRate);// add murder rate to string
return murderRateHigh;
}// end murderRateHigh method
/*
* murderRateLow method - outputs lowest year and rate
*/
public String murderRateLow () {
// declare variables
int year = 0;
float highestRate = 0;
String murderRateLow = "\n**** Lowest Murder Rate ****" +
"\n-----------------------------\n" +
"Year: ";
year = recordList.get(0).getYear();// store year of first record
highestRate = recordList.get(0).getMurderNonNegManslaughterRate();//store rate of first record
// loop through records and compare rates
for( int i = 1; i < recordList.size(); i++ ){
if(highestRate > recordList.get(i).getMurderNonNegManslaughterRate() ){ //if rate is lower
year = recordList.get(i).getYear();// store year
highestRate = recordList.get(i).getMurderNonNegManslaughterRate();//store rate
}// end if
}// end for loop
murderRateLow += Integer.toString(year); //add year to string
murderRateLow += " Murder Rate:";// add title to string
murderRateLow += Float.toString(highestRate);// add murder rate to string
//murderRateLow += yearLow;
return murderRateLow;
}// end murderRateLow method
/*
* robberyRateHigh method - outputs highest year and rate
*/
public String robberyRateHigh () {
// declare variables
int year = 0;
float highestRate = 0;
String robberyRateHigh = "\n**** Highest Robbery Rate ****" +
"\n-----------------------------\n";
year = recordList.get(0).getYear();// store year of first record
highestRate = recordList.get(0).getRobberyRate();//store rate of first record
// loop through records and compare rates
for( int i = 1; i < recordList.size(); i++ ){
if(highestRate < recordList.get(i).getRobberyRate() ){ //if rate is higher
year = recordList.get(i).getYear();// store year
highestRate = recordList.get(i).getRobberyRate();//store rate
}// end if
}// end for loop
robberyRateHigh += Integer.toString(year); //add year to string
robberyRateHigh += " Robbery Rate:";// add title to string
robberyRateHigh += Float.toString(highestRate);// add murder rate to string
return robberyRateHigh;
}// end robberyRateHigh method
/*
* robberyRateLow method - outputs lowest year and rate
*/
public String robberyRateLow () {
// declare variables
int year = 0;
float highestRate = 0;
String robberyRateLow = "\n**** Lowest Robbery Rate ****" +
"\n-----------------------------\n";
year = recordList.get(0).getYear();// store year of first record
highestRate = recordList.get(0).getRobberyRate();// store rate of first record
// loop through records and compare rates
for( int i = 1; i < recordList.size(); i++ ){
if(highestRate > recordList.get(i).getRobberyRate() ){ //if rate is lower
year = recordList.get(i).getYear();// store year
highestRate = recordList.get(i).getRobberyRate();//store rate
}// end if
}// end for loop
robberyRateLow += Integer.toString(year); //add year to string
robberyRateLow += " Robbery Rate:";// add title to string
robberyRateLow += Float.toString(highestRate);// add murder rate to string
return robberyRateLow;
}// end robberyRateLow method
}// end CrimeStatistics class
/*required imports*/
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/*
* CrimeDataRecords class - manages all CSV data extraction
* and build records
*/
public class CrimeDataRecords {
// declare Objects
private static BufferedReader fileIn; //BufferedReader to read csv file
private static List<CrimeDataObjects> dataRecords; // List to store CrimeDataObjects
/* default constructor*/
public CrimeDataRecords() {
}
/*
* compileData method - extract data from csv and pass to buidCrimeDataRecords
*/
public static void readData(){
//declare variables
String lineIn = null; // temporarily holds string from csv file
//initialize objects
UserInterface userFile;
try {
// instantiate Objects
userFile = new UserInterface();
fileIn = new BufferedReader(new FileReader(userFile.getFileToRead()));// get file path
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("File Not Found");
}// end try/catch
// instantiate List object
dataRecords = new ArrayList<CrimeDataObjects>();
try{
fileIn.readLine();// skip first line
lineIn = fileIn.readLine();//read line and store temporary String
/*while loop to read all lines from CSV file*/
while(lineIn != null){ //while the next line is not empty
//System.out.println(lineIn); uncomment to see data transfer in console
String[] parsedData = lineIn.split(",");//split strings and store to String array
buildCrimeDataObjects(parsedData); // call method and pass string array
lineIn = fileIn.readLine();// read next line and store to temporary String
}//end while loop
} catch (IOException e) {
e.printStackTrace();
}//end try/catch
}// end compileData method
/*
* buildCrimeDataRecords - builds CrimeDataObjects and stores them in List dataRecords
*/
public static void buildCrimeDataObjects(String[] parsedData){
String[] data = parsedData;
// initialize object
CrimeDataObjects csvRecord;
// parse strings to correct data type
int year = Integer.parseInt(data[0]);
long poplulation = Long.parseLong(data[1]);
long violentCrime = Long.parseLong(data[2]);
float violentCrimeRate = Float.parseFloat(data[3]);
int murderNonNegManslaughter = Integer.parseInt(data[4]);
float murderNonNegManslaughterRate = Float.parseFloat(data[5]);
int rape = Integer.parseInt(data[6]);
float rapeRate = Float.parseFloat(data[7]);
int robbery = Integer.parseInt(data[8]);
float robberyRate = Float.parseFloat(data[9]);
int aggravatedAssault = Integer.parseInt(data[10]);
float aggravatedAssaultRate = Float.parseFloat(data[11]);
int propertyCrime = Integer.parseInt(data[12]);
float propertyCrimeRate = Float.parseFloat(data[13]);
int burglery = Integer.parseInt(data[14]);
float burgleryRate = Float.parseFloat(data[15]);
int larceny = Integer.parseInt(data[16]);
float larcenyRate = Float.parseFloat(data[17]);
int motorVehicleTheft = Integer.parseInt(data[18]);
float motorVehicleTheftRate = Float.parseFloat(data[19]);
// instantiate CrimeDataRecords object and pass data parsed from csv
csvRecord = new CrimeDataObjects(year,poplulation,violentCrime,violentCrimeRate,murderNonNegManslaughter,
murderNonNegManslaughterRate,rape,rapeRate,robbery,robberyRate,
aggravatedAssault,aggravatedAssaultRate,propertyCrime,propertyCrimeRate,
burglery,burgleryRate,larceny,larcenyRate,motorVehicleTheft,motorVehicleTheftRate);
dataRecords.add(csvRecord);// add csvRecord object to List
}// end buildCrimeDataRecords
/*
* getdataRecord method - returns data records as a List
* it is static since all instances use the same data
*/
public static List<CrimeDataObjects> getDataRecords(){
return dataRecords;
}// end getDataRecors method
}// end Class
/*Required imports*/
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
/*
* UserInterface class- creates all user prompts, collects user input and
* calls methods to display statistics selected.
*/
public class UserInterface {
// declare variables
private static String fileToRead = ""; //file path
private double startTime = 0.0; //timer start time
private double endTime = 0.0; //timer end time
private final String CLEANSPACE = "\n\n\n"; //used to create space in data output
Scanner input;
//default constructor
public UserInterface(){
}
// constructor with file path argument
public UserInterface(String filePath) {
setFileToRead(filePath);// call method to set file path
}
/*
* getter method for fileToRead
*/
public String getFileToRead() {
return fileToRead;
}
/*
* setter method for fileToRead
* re formats file path for specific OS.
*/
public void setFileToRead(String filePath) {
// declare local variable
String file = filePath;
//get OS file separator an rebuild file path string
char separator = java.io.File.separatorChar;//get system default file separator
if(separator != '/'){ // if file separator is not / (if Windows)
String windowsFilePath = file.replace('/', '\\');
filePath = windowsFilePath;
}//end if separator != '\'
// set fileToRead variable with file path
fileToRead = file;
}// end setFileToRead method
/*
* setter method for startTime
*/
public void setStartTime() {
this.startTime = System.nanoTime();
}// end setStartTime method
/*
* getter method for startTime
*/
public double getStartTime() {
return startTime;
}// end getStartTime method
/*
* setter method for endTime
*/
public void setEndTime() {
this.endTime = System.nanoTime();
}// end setEndTime method
/*
* getter method for endTime
*/
public double getEndTime() {
return endTime;
}// end getEndTime method
/*
* initialize method - initializes the user interface
*/
public void intitialize() {
welcomePrompt();
//initialize Scanner object
input = new Scanner(System.in);
setFileToRead(input.nextLine());//set file to read from user input
//check if file exist
File file = new File(getFileToRead()); // instantiate File object and pass it file path
if(file.exists()){ // if file exists
setStartTime(); // set start time
menu(); // call selection menu
}else{ // if file does not exist
System.out.println("\n**File does not exist**");
System.out.println("1). Enter 'Q' to Quit");
System.out.println("2). Enter any charachter to re enter file path");
System.out.print("Enter your selection: ");
if(input.next().toUpperCase().compareTo("Q") != 0){ // user does not quit
intitialize(); // call initialize method to re enter file path
}else{
System.exit(0);
}//end if
}//end if
input.close(); // close scanner
}//end initialize method
/*
* welcomeScreen method - displays initial welcome screen and user prompts
*/
public void welcomePrompt(){
//user prompts
System.out.println("\n*** Welcome to The US Crime Statistical Application***\n");
System.out.println(" - Please enter the file path to start.");
System.out.println(" - Please use / as path seperator: Example C:/user/file");
System.out.print("File: ");
}// end welcomePrompt method
/*
* menu method - displays menu of options
*/
public void menu() {
System.out.println(CLEANSPACE);
System.out.println("******************** Welcome to The US Crime Statistical Application ********************");
System.out.println("\n\nEnter the number of the question you want answered. Enter 'Q' to quit the program:\n");
System.out.println("1. What were growth 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");
System.out.print("\nEnter your selection: ");
userSelection();//call user selection
}// end menu method
/*
* userSelection method - gets user input selection from menu items
*/
public void userSelection() {
// declare variables
String userInput; // holds user selection
// initialize Scanner object
input = new Scanner(System.in);
userInput = input.next().toUpperCase(); // assign user input to variable
statisticSelection(userInput); // pass user input to statisticSelection method
input.close(); // close scanner
}//end userSelection method
/*
* secondOptionSelection method - gets user input continue or quit prompt
* that shows after first statistic is displayed
*/
public void optionToQuit() {
//declare variables
String userInput;
//initialize scanner
input = new Scanner(System.in);
System.out.println("\nEnter 'C' for menu or 'Q' to quit");
userInput = input.next().toUpperCase(); // get user selection
//validate second option menu
if(userInput.compareTo("C") == 0){ // if continue is selected
menu(); // call menu to be displayed
}else if (userInput.compareTo("Q") == 0){ // if quit is selected
statisticSelection(userInput);// pass user selection to switch statement in statistic selection
}else{ // if invalid entry
System.out.println("**Invalid selection - Returning to menu**.\n\n\n\n");
menu(); // call menu to be displayed
}//end if
input.close(); // close scanner
}//end userSelection method
/*
* statisticSelection method - takes the user input and calls the method to
* display statistics
*/
public void statisticSelection(String seclection){
// declare variables
boolean askContinue = false; //used to validate if continue or quit menu should be displayed
// instantiate CrimeStatistic object
CrimeStatistics statistic = new CrimeStatistics();
System.out.println(CLEANSPACE); //create space in output
// switch statement to select correct statistic to be displayed
switch(seclection){
case "1": ArrayList<String> growthRateChart = statistic.popGrowthRate(); // population growth rate chart
for(String year : growthRateChart)
System.out.println(year);
askContinue = true;
break;
case "2": System.out.println(statistic.murderRateHigh()); // year of highest murder rate
askContinue = true;
break;
case "3": System.out.println(statistic.murderRateLow()); // year of lowest murder rate
askContinue = true;
break;
case "4": System.out.println(statistic.robberyRateHigh()); // year of highest robbery rate
askContinue = true;
break;
case "5": System.out.println(statistic.robberyRateLow()); // year of lowest robbery rate
askContinue = true;
break;
case "Q": setEndTime(); // user quits - set end time
System.out.println(elsapsedTime()); //output elapsed time
System.exit(0); // exit
break;
case "C": menu(); // continue to menu of selections
break;
default: System.out.println("\n\n**Invalid Entry. Please re enter your selection**\n"); // if user makes invalid selection
menu(); // call selection menu
break;
}//end switch statement
// if a statistic has been called then display continue or quit
if(askContinue){ // if boolean has been triggered from statistic being selected
optionToQuit(); // call continue or quit
askContinue = false; //re set boolean
}//end if
}//end userInput method
/*
* elapsedTime method - calculates and returns elapsed time
*/
public String elsapsedTime(){
double time = (getEndTime() - getStartTime())/1000000000.0; // calculate elapsed time
String elapsedTime = ("\n***Elapsed Time: " + Math.round(time) + " seconds***\n");
elapsedTime += "***Thank you for using the US Crime Statistics Program***\n\n";
return elapsedTime;
}// end elapsedTime method
}// end userInterface Class
/*
* Class TestUserInterface - tests the UserInterface class and runs the program
*/
public class TestUserInterface {
//main method
public static void main(String[] args){
//instantiate UserInterface object
UserInterface userInterface = new UserInterface();
userInterface.intitialize();// call initialization method
}//end main
}// end TestUserInterface class
public class CrimeDataObjects {
//declare variables
private int year = 0; //year
private double poplulation = 0; //population
private long violentCrime = 0; //violent crime
private float violentCrimeRate = 0; //violent crime rate
private int murderNonNegManslaughter = 0; //Murder and non-negligent manslaughter
private float murderNonNegManslaughterRate = 0;//Murder and non-negligent manslaughter rate
private int rape = 0;//rape
private float rapeRate = 0;//rape rate
private int robbery = 0; //robbery
private float robberyRate = 0;//robbery rate
private int aggravatedAssault = 0;//Aggravated assault
private float aggravatedAssaultRate = 0;//Aggravated assault rate
private int propertyCrime = 0;//Property crime
private float propertyCrimeRate = 0;//Property crime rate
private int burglary = 0; //Burglary
private float burglaryRate = 0;//Burglary rate
private int larceny = 0;//larceny
private float larcenyRate = 0;//larceny rate
private int motorVehicleTheft = 0;//motor vehicle theft
private float motorVehicleTheftRate = 0;//motor vehicle theft rate
//default constructor
public CrimeDataObjects(){
}
//constructor
public CrimeDataObjects(int year, double poplulation, long vCrime, float vCrimeRate,
int murderNonNegMan, float murderNonNegManRate, int rape,
float rapeRate, int robbery,float robberyRate, int aggAssault,
float aggAssaultRate, int propCrime, float propCrimeRate, int burglery,
float burgleryRate,int larceny, float larcenyRate, int mvTheft, float mvTheftRate ) {
this.year = year;
this.poplulation = poplulation;
this.violentCrime = vCrime;
this.violentCrimeRate = vCrimeRate;
this.murderNonNegManslaughter = murderNonNegMan;
this.murderNonNegManslaughterRate = murderNonNegManRate;
this.rape = rape;
this.rapeRate = rapeRate;
this.robbery = robbery;
this.robberyRate = robberyRate;
this.aggravatedAssault = aggAssault;
this.aggravatedAssaultRate = aggAssaultRate;
this.propertyCrime = propCrime;
this.propertyCrimeRate = propCrimeRate;
this.burglary = burglery;
this.burglaryRate = burgleryRate;
this.larceny = larceny;
this.larcenyRate = larcenyRate;
this.motorVehicleTheft =mvTheft;
this.motorVehicleTheftRate = mvTheftRate;
}
/*
* getter method for year
*/
public int getYear() {
return year;
}
/*
* getter method for population
*/
public double getPoplulation() {
return poplulation;
}
/*
* getter method for violentCrime
*/
public long getViolentCrime() {
return violentCrime;
}
/*
* getter method for violentCrimeRate
*/
public float getViolentCrimeRate() {
return violentCrimeRate;
}
/*
* getter method for murderNonNegManslaughter
*/
public int getMurderNonNegManslaughter() {
return murderNonNegManslaughter;
}
/*
* getter method for murderNonNegManslaughterRate
*/
public float getMurderNonNegManslaughterRate() {
return murderNonNegManslaughterRate;
}
/*
* getter method for rape
*/
public int getRape() {
return rape;
}
/*
* getter method for rapeRate
*/
public float getRapeRate() {
return rapeRate;
}
/*
* getter method for robbery
*/
public int getRobbery() {
return robbery;
}
/*
* getter method for robberyRate
*/
public float getRobberyRate() {
return robberyRate;
}
/*
* getter method for aggravatedAssault
*/
public int getAggravatedAssault() {
return aggravatedAssault;
}
/*
* getter method for aggravatedAssaultRate
*/
public float getAggravatedAssaultRate() {
return aggravatedAssaultRate;
}
/*
* getter method for propertyCrime
*/
public int getPropertyCrime() {
return propertyCrime;
}
/*
* getter method for propertyCrimeRate
*/
public float getPropertyCrimeRate() {
return propertyCrimeRate;
}
/*
* getter method for burglary
*/
public int getBurglery() {
return burglary;
}
/*
* getter method for burgleryRate
*/
public float getBurgleryRate() {
return burglaryRate;
}
/*
* getter method for larceny
*/
public int getLarceny() {
return larceny;
}
/*
* getter method for larcenyRate
*/
public float getLarcenyRate() {
return larcenyRate;
}
/*
* getter method for motorVehicleTheft
*/
public int getMotorVehicleTheft() {
return motorVehicleTheft;
}
/*
* getter method for motorVehicleTheftRate
*/
public float getMotorVehicleTheftRate() {
return motorVehicleTheftRate;
}
}// end CrimeDataObjects cla
ss