Crime statistics homework assistance - java

I am trying to get this to work but it keeps saying the file is unfindable when you type the location.. I want the user to be able to put the location of the file that is needed to be read. I cannot figure out how to stop the errors. Any help would be appreciated. The output allows me to type a file location but after that it errors.
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

Related

Java menu displaying twice after input

Hey guys I have been working on this program for class the past couple hours and just cant seem to get these last 2 issues resolved. Its basically a slightly modified CashRegister class with basic functions through a menu. The problems I am having are:
1) After the user makes a menu selection for the first time, every subsequent time the menu shows up in console twice and I cant seem to find a fix for this.
2) Also whenever I choose to display the content of my CashRegister, the first line is always output as 0.00 no matter the input.
Here is my CashRegister class followed by my tester:
import java.util.ArrayList;
/**
*
*/
/**
* #author Cole
*
*/
public class CashRegister {
private double dailyTotal;
private double totalPrice;
ArrayList<Double> items;
/**
Constructs a cash register with cleared item count and total.
*/
public CashRegister()
{
items = new ArrayList<Double>();
dailyTotal = 0;
totalPrice= 0;
}
/**
Adds an item to this cash register.
#param price the price of this item
*/
public void addItem(double price)
{
items.add(price);
dailyTotal = dailyTotal + price;
}
/**
Gets the price of all items in the current sale.
#return the total amount
*/
public double getTotal()
{
for(int x=0; x<items.size(); x++){
totalPrice = totalPrice + items.get(x);
}
return totalPrice;
}
/**
Gets the number of items in the current sale.
#return the item count
*/
public int getCount()
{
return items.size();
}
/**
Clears the item count and the total.
*/
public void clear()
{
items.clear();
totalPrice = 0;
}
public void display(){
for(int x=0; x<items.size(); x++){
System.out.printf("%10.2f%n", items.get(x));
}
System.out.println("------------------------------");
}
public double getDailyTotal(){
dailyTotal = dailyTotal + totalPrice;
return dailyTotal;
}
}
import java.util.ArrayList;
import java.util.Scanner;
/**
*
*/
/**
* #author Cole
*
*/
public class Prog2 {
/**
* #param args
*/
public static final String MENU = "******************************************\n" +
"* Enter \"n\" to start a new Cash Register. *\n" +
"* Enter \"a\" to add an item to the current Cash Register. *\n" +
"* Enter \"d\" to display the total of the current Cash Register. *\n" +
"* Enter \"e\" to exit the program. *\n" +
"******************************************";
public static final String NEW_CUSTOMER = "n";
public static final String ADD_ITEM = "a";
public static final String DISPLAY = "d";
public static final String EXIT = "e";
public static void main(String[] args) {
// TODO Auto-generated method stub
CashRegister register = new CashRegister();
Scanner keyboard = new Scanner(System.in);
String input;
double userInput = 0;
do {
input = printMenu(keyboard);
if(input.equals(NEW_CUSTOMER)){
register.getDailyTotal();
register.clear();
}
else if(input.equals(ADD_ITEM)){
System.out.println("Please enter the price of the item: ");
register.addItem(userInput);
userInput = keyboard.nextDouble();
}
else if(input.equalsIgnoreCase(DISPLAY)){
register.display();
System.out.println("Total: " + register.getTotal());
System.out.println("Item Count: " +register.getCount());
}
else if(input.equalsIgnoreCase(EXIT)){
System.out.printf("Daily Sales Total: " + "%.2f%n",register.getDailyTotal());
System.out.println("Program Ended...");
break;
}
}while(input != EXIT);
}
public static String printMenu(Scanner input){ //this method displays the menu for the user
String response = "no reponse yet";
System.out.println(MENU);
response = input.nextLine();
return response; //response returned based on the users input
}
}
You need to get input from the user before you add the item, that's why you are getting a 0 for your first item. Since your value for userInput is set to 0 at the beginning and your statements are switched you will always initialy create an item with 0.0 for it's value and all the other values will be one step behind the actual inputs.
else if(input.equals(ADD_ITEM)){
System.out.println("Please enter the price of the item: ");
userInput = keyboard.nextDouble();
register.addItem(userInput);
}

Java Basic Object Oriented Gratuity Calculator

I'm beginning to learn more about Java and I'm trying to code a Gratuity calculator that takes user Input, and shows how much a tip would be at %10 and %20 of the total. I'm getting a single "Cannot make a static reference to the non-static method" error that I can't resolve.
Gratuity class:
public class Gratuity{
//variables
private double total = 0;
private double grat1 = 0;
private double grat2 = 0;
public Gratuity(float value){
total = value;
}
start getters and setters
public double getTotal() {
return total;
}
//method to do the calculations
public void calcGrat(){
grat1 = total * .10;
grat2 = total * .20;
}
public double getGrat1(){
return grat1;
}
}
And the class with the main method:
import java.util.InputMismatchException;
import java.util.Scanner; //import package to use the scanner input function
//TestGrat main class contains method
public class TestGrat {
Scanner keyboard = new Scanner(System.in);
//method to prompt user for total, double is total
public void askForInput(){
try{
System.out.println("Enter the total amount of your bill");
total = keyboard.nextDouble();
}
catch(InputMismatchException e){
System.err.printf("Error, please try again. Program will now close");
System.exit(0);
}
}
public Scanner getKeyboard() {
return keyboard;
}
public void setKeyboard(Scanner keyboard) {
this.keyboard = keyboard;
}
//main method
public static void main(String[] args){
// asks for input in float form
float value = askForInput();
//Creating the gratCalc object and storing value as a float (total)
Gratuity gratCalc = new Gratuity(value);
// get the total value and set as float
float tot = (float)gratCalc.getTotal();
// converting the float value into string
System.out.println("You have entered: " + Float.toString(tot));
gratCalc.calcGrat(); //sets grat
// Displaying the options to user
System.out.println("Below are the tips for %10 as well as %20 ");
//getting the value and then displaying to user with toString
float getNum = (float) gratCalc.getGrat1();
float getNum1 = (float) gratCalc.getGrat2();
// using the value of getNum as float to put into toString
System.out.println( "For %10: " + Float.toString(getNum));
System.out.println(" For %20: " + Float.toString(getNum1));
}
}
Any help would be appreciated. Thanks!
askForInput() is inside your class TestGrat. However, in main() you are calling it directly, as if it was static. You probably meant:
TestGrat test = new TestGrat();
float value = test.askForInput();
askForInput() is also returning void, so you probably want to fix that too.

Read data from text file print to terminal and new text file

I want to read data from a text file and print the output to both the terminal and a text file. I have a loop that reads for numbers and one that reads for non-numerical characters, but nothing is printing out to the terminal. i am new to programming.
I am transforming an old project to a new one by the way.
package studenttester;
public class Student
{
private String name;
double quizScore;
double quizAverage;
private int numQuizzes;
String grade;
/**
* Returns the name of a student
*
* #return the name of the student
*/
public Student (String inName)
{
name = inName;
quizAverage = 0;
quizScore = 0;
numQuizzes = 0;
}
public String getName()
{
return name;
}
/**
* Adds a quiz score to the total quiz score of the student
*
* #param score the score of a quiz
*/
void addQuiz(int score)
{
numQuizzes += 1;
quizScore += score;
}
/**
* Returns the total score of all the quizzes combined that student took
*
* #return the value of score
*/
double getTotalScore()
{
return quizScore;
}
/**
* Returns the average score of all the quizzes a student took
*
* #return
*/
double getAverageScore()
{
return quizScore / numQuizzes;
}
}
package studenttester;
import java.io.*;
import java.util.Scanner;
public class StudentTester {
public static void main(String[] args) throws FileNotFoundException
{
System.out.println("Student Name Number of Quizzes Average");
Scanner reader = new Scanner(new File("quizScores.txt"));
String studentName = "", first="", last="";
while (!reader.hasNext("-10"))
{
}
while (reader.hasNextDouble())
{
first = first+reader.next();
studentName = last + first;
}
Student newStudent = new Student(studentName);
while (reader.hasNextDouble() && !reader.hasNext("-10"))
{
System.out.printf("");
}
{
// writer.close;
}
}
}
The "red underline" means an compiler error, I guess.
Have a look to your while loop, it seems to be wrong.
Try ...
while (reader.hasNextDouble() && (!reader.hasNext("-10")))
System.out.printf("");
}
reader.close();
instead.

Formatting an output

having trouble with my output. It prints in the correct format as long as the last digit isn't a zero. In other words, it will output $1.75 but for $1.50 I get $1.5. I know the "%.2f" is supposed to format it but I can't figure out where to put it in my code. Thanks!
/**
This Class is designed to work with an application program for a Vending Machine.
*/
public class VendingMachine
{
private double money;
private double amountDue;
private double change;
private String selection;
/**
Constructor for the Class.
*/
public VendingMachine()
{
money = 0.00;
amountDue = 0.00;
change = 0.00;
selection = "";
}
/**
Explicit Constructor for the class that gives variables more specific values.
*/
public VendingMachine(double money, double change, double amountDue, String selection)
{
this.money = money;
this.amountDue = amountDue;
this.change = change;
this.selection = selection;
}
/**
Accesssor method for the selection.
#return the selection of the user.
*/
public String getSelection()
{
return selection;
}
/**
Accessor method to get the amount of money the user puts in the machine.
#return the amount of money.
*/
public double getMoney()
{
return money;
}
/**
Accessor method for the amount due.
#return the amount due.
*/
public double getAmountDue()
{
return amountDue;
}
/**
Accessor method for getting the user's change.
#return the user's change.
*/
public double getChange()
{
return change;
}
/**
Mutator method for the selection.
#param the selection of the user.
*/
public void setSelection(String selection)
{
this.selection = selection;
}
/**
Mutator method for money.
#param the money put into machine.
*/
public void setMoney(double money)
{
this.money = money;
}
/**
Mutator method for amount due.
#param the selection of the user.
*/
public double setAmountDue(String selection)
{
if (selection.equals("A1") || selection.equals("A2") || selection.equals("A3"))
{
amountDue = 1.25;
}
else if (selection.equals("B1") || selection.equals("B2") || selection.equals("B3"))
{
amountDue = 1.00;
}
else if (selection.equals("C1") || selection.equals("C2") || selection.equals("C3"))
{
amountDue = 1.50;
}
return amountDue;
}
/**
Mutator method for the change.
#param the money put into machine.
*/
public void setChange(double money)
{
change = money - amountDue;
this.change = change;
}
/**
Method for converting all variables into a String statement.
#return a String of the total transaction.
*/
public String toString()
{
return ("Your selection: " + selection + "\nYour amount due: " + amountDue + "\nYour change: " + change);
}
}
import java.util.*;
/**
This program runs a Vending Machine and interacts with the user.
*/
public class VendingMachineTester
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String input;
String[] choices = {"A1~~SNICKERS~~~~~~~~$1.25", "A2~~MILKY WAY~~~~~~~$1.25" , "A3~~TWIX~~~~~~~~~~~~$1.25",
"B1~~ORIGINAL CHIPS~~$1.00", "B2~~BBQ CHIPS~~~~~~~$1.00" , "B3~~PRETZELS~~~~~~~~$1.00",
"C1~~COKE~~~~~~~~~~~~$1.50", "C2~~SPRITE~~~~~~~~~~$1.50", "C3~~DR. PEPPER~~~~~~$1.50",
};
displayItems(choices);
VendingMachine user = new VendingMachine();
do
{
System.out.print("Please make your selection: ");
input = in.nextLine();
}
while (!(input.equals("A1") || input.equals("A2") || input.equals("A3") ||
(input.equals("B1") || input.equals("B2") || input.equals("B3") ||
(input.equals("C1") || input.equals("C2") || input.equals("C3")))));
user.setSelection(input);
user.setAmountDue(input);
System.out.print("Enter the amount you put in the machine: ");
double amount = in.nextDouble();
user.setMoney(amount);
user.setChange(amount);
System.out.println(user);
System.out.print("Thank You for your purchase!");
}
/**
A method for displaying all of the options in the machine.
#param an array of choices
#return an array of choices.
*/
public static void displayItems(String[] choices)
{
for (int i = 0; i < choices.length; i++)
{
System.out.print(choices[i]);
System.out.println();
}
return;
}
}
This should do the trick:
public String toString() {
return String.format( "Your selection: %s: \nYour amount due: %.2f \nYour change: %.2f",
selection,
amountDue,
change);
}

List and arraylist initialization and use

I'm attempting to create a list because of the ability to "add" and element as opposed to checking size then dynamically expanding an array every time a new element is input. I can't get this to compile. I've scoured stack and google and nothing I've found is helping me. Someone mentioned creating an array and using that to be added to the list, but it seems to me i should be able to do this without all that.
I'm trying to get the system to add a string to the list every time a certain result occurs.
For ease of finding the List is called "incorrect"
import java.text.DecimalFormat;
import java.util.*;
public class User{
private String wrongQuestion; //quiz question
private String userName; //store user name
private String myOutput; //store output for toString and file write
private int score; //store user current score
private float average; //store user average score
private int diffLevel; //difficulty level
private int testType; //last test type
private int numTests; //store number of tests taken
private List <String> incorrect; //declare list for incorrect answers
private FileIO uFile; //declare FileIO object
public User(String inName) throws Exception
{
//local constants
final int VARIABLE_COUNT = 5; //loop sentinel
final int TOKEN_SKIP = 4; //loop sentinel
//local variables
int index; //loop index
int count; //loop counter
String token; //store tokens from line
StringTokenizer tokenLine; //store tokenized line
//instantiate file object
uFile = new FileIO (inName);
//if user exists
if (uFile.checkUser())
{
for (count = 0; count < VARIABLE_COUNT; count++)
{
//initialize tokenized line
tokenLine = new StringTokenizer(uFile.readLine());
//try to store the variables
try
{
//get and store user average
//for the first 2 tokens, skip
for (index = 0; index < TOKEN_SKIP; index++)
{
//move to next token
token = tokenLine.nextToken();//end for
switch (count)
{
case 1:
//store number of tests taken
numTests = Integer.parseInt(token);
//end case
break;
case 2:
//store difficulty of last test taken
diffLevel = Integer.parseInt(token);
//end case
break;
case 3:
//store score of last test taken
score = Integer.parseInt(token);
//end case
break;
case 4:
//store average of tests taken
average = Integer.parseInt(token);
//end case
break;
default:
break;
}//end switch
}//end for
//store next line
token = uFile.readLine();
//while there are more lines in the file
while (token != null)
{
//instantiate list for incorrect answers
incorrect = new ArrayList<String>();
//add line to end of list
incorrect.get(token);
//store next line
token = uFile.readLine();
}//end while
}//end try
//catch input mismatch exception
catch (InputMismatchException error)
{
//output error message
System.out.println ("This file is not formatted properly." +
" Either continue as a new user or log in again");
//initialize data to 0
average = 0;
testType = 0;
diffLevel = 0;
numTests = 0;
incorrect = new ArrayList <String>();
}//end catch
}//end for
}//end if
else
{
//initialize data to 0
average = 0;
testType = 0;
diffLevel = 0;
numTests = 0;
incorrect = new ArrayList<String>();
}//end else
//close input stream
uFile.closeFileReader();
}//end constructor
public float calcAverage(int newScore)
{
//local constants
//local variables
float avg; //store temp average
/**************Begin calcAverage*********/
//recalibrate avg for new calculation
avg = 0;
//calculate new average test score
avg = ((average * numTests) + newScore )/(numTests + 1);
//return average to be stored
return avg;
}
public void updateUser(int newTestType, int newDiffLevel, int newScore)
{
//local constants
//local variables
/***************Begin updateUser************/
//update new data after test is taken
score = newScore;
average = calcAverage(newScore);
diffLevel = newDiffLevel;
testType = newTestType;
numTests = numTests + 1;
}
public void writeFile() throws Exception
{
//local constants
//local variables
String line; //current line to write to file
int index; //loop index
/*************************Begin writeFile***************/
//open output stream
uFile.openOutput(userName);
//write user name
line = "User Name:\t" + userName +"\n";
uFile.writeLine(line);
//write number of tests taken
line = "Tests Taken:\t" + numTests + "\n";
//write number of tests taken
line = "Difficulty Level:\t" + diffLevel + "\n";
uFile.writeLine(line);
//write score of last test taken
line = "Last Test:\t" + score + "\n";
uFile.writeLine(line);
//write current user average
line = "User Average:\t" + average + "\n";
uFile.writeLine(line);
//for each element in the list
for (index = 0; index < incorrect.size(); index++)
{
//store then write the string
line = incorrect.get(index);
uFile.writeLine(line);
}//end for
//close file writer
uFile.closeFileWrite();
}//end writeFile
public void storeIncorrect(String inString)
{
//local constants
//local variables
/************Begin storeIncorrect*************/
//add formatted question to the list
incorrect.add(inString);
}
public String toString()
{
//local constants
//local variables
String buildUserName;
String buildAvg;
String buildNumTests;
String buildDiffLevel;
String buildScore;
DecimalFormat fmt; //declare decimal format object
/****************Begin toString***********/
//initialize decimal format
fmt = new DecimalFormat ("0.00");
//build output strings
buildUserName = Util.setLeft(20, "User Name:") + Util.setRight(25, userName);
buildNumTests = Util.setLeft(20, "Tests Taken:") + Util.setRight(18, numTests+"");
buildDiffLevel = Util.setLeft(20, "Last Difficulty:") + Util.setRight(24, diffLevel+"");
buildScore = Util.setLeft(20, "Last Score:") + Util.setRight(24, score+"");
buildAvg = Util.setLeft(20, "Test Average:") + Util.setRight(24, fmt.format(average)+"");
myOutput = buildUserName + "\n" + buildNumTests + "\n" + buildDiffLevel + "\n" + buildScore + "\n" + buildAvg;
return myOutput;
}//Display all users info
}
Few comments that might help :
// add line to end of list
incorrect.get(token); // <- change this to incorrect.add(token)
To iterate thru list use :
for (String item : incorrect) {
System.out.printlnt(item);
}
Also, you don't need to reinitialize your list as you do multiple times by
incorrect = new ArrayList<String>();
If you'd like to clear it, you could use incorrect.clear()
As you are not interested in Random access (i.e. via index), perhaps you could use LinkedList instead of ArrayList

Categories