Java menu displaying twice after input - java

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);
}

Related

Crime statistics homework assistance

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

Creating transcripts in java using array

so im very new to programming so sorry if is an inane question
But i have been given a homework where i have to create a transcript with java using array,
first i have to enter the students name and code, then the peogram should tell me to enter each lesson’s grade individually
And the result should display the student’s name,code and the grades i have entered for each lecture
I know how to enter make the program prompt me with each lecture and grade entry but showing all the grades i have entered next to thier lecture is what im stuck on
I would highly appreciate it if i get an answer.
Thanks
Take a look at this code, if there is something obscure, ask for clarification.
MainClass.java class
public class MainClass {
static boolean flag = true;
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
//create new student
Student student = new Student();
//print out enter name of a student
System.out.println("Enter name of student: ");
//read students name from next line
student.setNameOfStudent(keyboard.nextLine());
//print out enter code of a student
System.out.println("Enter code of student: ");
//read students password from a next line
student.setPasswordOfStudent(keyboard.nextLine());
//create a list of lectures to add them to a student
List<Lecture> lectures = new ArrayList<>();
//do adding lectures and grades for them while N is not pressed
do {
// enter new lecture name
System.out.println("Add a lecture? Y or N ");
//take answer for adding a lecture from a next input
String answerForAddingLecture = keyboard.next();
//if answer is yes
if ("Y".equalsIgnoreCase(answerForAddingLecture)) {
// print enter a name of a lecture
System.out.println("Enter a name of a lecture? ");
//take a lecture name from next input
String lectureName = keyboard.next();
// create a lecture
Lecture lecture = new Lecture();
// set lecture name from lectureName variable
lecture.setNameOfLecture(lectureName);
//create a list of grades
List<Grade> listOfGrades = new ArrayList<>();
//do inside brackets while flag is set to true
do {
//print Add a grade for this lecture? Y or N
System.out.println("Add a grade for this lecture? Y or N ");
//set an answer variable from the next input
String answer = keyboard.next();
//if answer is yes
if ("Y".equalsIgnoreCase(answer)) {
//print what grade is it going to be?
System.out.println("What grade is it going to be?");
//create new grade object
Grade grade = new Grade();
//set temp variable to next int input
int temp = keyboard.nextInt();
//set grade value to the value of temp variable
grade.setGrade(temp);
// add this grade to a list of grades
listOfGrades.add(grade);
}
//if answer is negative
else if ("N".equalsIgnoreCase(answer)) {
//set flag to false
flag = false;
}
}
//do above as long as flag is set to true
while (flag);
//reset flag to true again for keep adding new lectures
flag = true;
//set a list of grades to a lecture grades list
lecture.setGradesOfLecture(listOfGrades);
//set a lecture to a list of lectures
lectures.add(lecture);
//set a list of lectures to a students lecture list
student.setLecturesOfStudent(lectures);
}
//if answer is negative
else if ("N".equalsIgnoreCase(answerForAddingLecture)) {
flag = false;
}
} while (flag);
//print a student with all lectures and grades
System.out.println(student.toString());
}
}
Student.java class
public class Student {
private String nameOfStudent;
private String passwordOfStudent;
private List<Lecture> lecturesOfStudent;
public Student() {
}
public Student(String nameOfStudent, String passwordOfStudent, List<Lecture> lecturesOfStudent) {
this.nameOfStudent = nameOfStudent;
this.passwordOfStudent = passwordOfStudent;
this.lecturesOfStudent = lecturesOfStudent;
}
/**
* #return the nameOfStudent
*/
public String getNameOfStudent() {
return nameOfStudent;
}
/**
* #param nameOfStudent the nameOfStudent to set
*/
public void setNameOfStudent(String nameOfStudent) {
this.nameOfStudent = nameOfStudent;
}
/**
* #return the passwordOfStudent
*/
public String getPasswordOfStudent() {
return passwordOfStudent;
}
/**
* #param passwordOfStudent the passwordOfStudent to set
*/
public void setPasswordOfStudent(String passwordOfStudent) {
this.passwordOfStudent = passwordOfStudent;
}
/**
* #return the lecturesOfStudent
*/
public List<Lecture> getLecturesOfStudent() {
return lecturesOfStudent;
}
/**
* #param lecturesOfStudent the lecturesOfStudent to set
*/
public void setLecturesOfStudent(List<Lecture> lecturesOfStudent) {
this.lecturesOfStudent = lecturesOfStudent;
}
public String getLecturesWithGrades() {
String temp = "\nLectures:";
for (Lecture l : getLecturesOfStudent()) {
temp += "\n" + l.getNameOfLecture();
temp += "\nGrades:\n";
for (Grade g : l.getGradesOfLecture()) {
temp += g.getGrade() + " ";
}
}
return temp;
}
#Override
public String toString() {
return "Student: " + getNameOfStudent() + " with a code: " + getPasswordOfStudent() + getLecturesWithGrades();
}
}
Lecture.java class
public class Lecture {
private String nameOfLecture;
private List<Grade> gradesOfLecture;
public Lecture() {
}
public Lecture(String nameOfLecture, List<Grade> gradesOfLecture) {
this.nameOfLecture = nameOfLecture;
this.gradesOfLecture = gradesOfLecture;
}
public String getNameOfLecture() {
return nameOfLecture;
}
public List<Grade> getGradesOfLecture() {
return gradesOfLecture;
}
public void setNameOfLecture(String nameOfLecture) {
this.nameOfLecture = nameOfLecture;
}
public void setGradesOfLecture(List<Grade> gradesOfLecture) {
this.gradesOfLecture = gradesOfLecture;
}
#Override
public String toString() {
return getNameOfLecture() + " " + getGradesOfLecture();
}
}
Grade.java class
/**
* Might add remarks on grades or any other properties some time later, therefore new
* object is created called Grade.
* #author
*/
public class Grade {
int grade;
public Grade() {
}
public Grade(int grade) {
this.grade = grade;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
#Override
public String toString() {
return getGrade() + " ";
}
}

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.

Amend all values in an Arraylist

I have a lab for my Programming I class where we need to design a program that uses an ArrayList of resistances to calculate the total resistance of a parallel and series circuit. For the parallel circuit, I need to change every item in the ArrayList to its reciprocal (1/item). I got to this point and cannot seem to find why this is wrong and a possible way around it. Thanks.
**the error I get is "The method get(int) in the type ArrayList is not applicable for the arguments (double)" for the line " resistances = 1 / resistances.get(index);" **
-businesslogic class-
import java.util.ArrayList;
/**
* The class Circuit gathers the resistances of a user-defined number of
* resistors for a user-defined type of circuit and displays the total
* resistance of the circuit for the main method of the Presentation class.
*/
public class Circuit {
private double arrayListSize;
public double n;
public double sum;
public double finalSum;
public ArrayList<Double> resistances = new ArrayList<Double>();
/**
* #param initialPop
* user-defined initial population
*/
public final void setArraySize(final double alSize) {
arrayListSize = alSize;
}
public final double getArraySize() {
return arrayListSize;
}
public final void setResistors(double alResistances) {
for (n = 0; n < getArraySize(); n++) {
resistances.add(alResistances);
}
}
public ArrayList<Double> getResistors() {
return resistances;
}
public final void setPResistance(ArrayList<Double> resistances) {
for (double index : resistances) {
resistances = 1 / resistances.get(index);
}
sum = 0;
for (double i : resistances) {
sum =sum + i;
}
double finalSum = 1 / sum;
}
public final double getPResistance() {
return finalSum;
}
}
-presentation class-
import java.util.Scanner;
/**
* The Class Presentation
*/
public class Presentation {
/**
* The main class uses the Circuit class and user input
* to calculate the total resistance of a circuit.
*
* #param args
* command line arguments
*/
public static void main(final String[] args) {
Scanner keyboard = new Scanner(System.in);
Circuit resistanceTotal = new Circuit();
System.out.println("This program will calculate the"
+ " total resistance of either a parallel or "
+ " a series circuit.\n");
System.out.println("Would you like to calculate the"
+ " resistance of a parallel circuit (1) or a"
+ " series circuit (2)?");
int userChoice = keyboard.nextInt();
System.out.println("How many resistors are there in the circuit?");
resistanceTotal.setArraySize(keyboard.nextDouble());
System.out.println("Enter resistance of resistor #" + (resistanceTotal.n + 1));
resistanceTotal.setResistors(keyboard.nextDouble());
resistanceTotal.getResistors();
if (userChoice == 1) {
resistanceTotal.setPResistance(resistanceTotal.getResistors());
resistanceTotal.getPResistance();
}
if (userChoice != 1 & userChoice != 2) {
System.out.println("You must enter 1 or 2!!!");
}
keyboard.close();
}
}
Your error is in this the setPResistance method. The method arrayList.get(i) takes a int value as a parameter, and you passed it the actual value of the position, which is a double.
To replace each item in the arraylist to its reciprocal, change the method like so:
public final void setPResistance(ArrayList<Double> resistances) {
for (int c = 0; c < resistances.size(); c++) {
resistances.set(c, 1/resistances.get(c));
}
}
Java docs on the set(int index, Double element) method:
Replaces the element at the specified position in this list with the
specified element.

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);
}

Categories