Cannot break small payroll system in different methods - java

I want to start by saying that I'm a newby in Java, and it's also my first time asking something on this site. After 3 days trying to figure out how to break this small program in methods, I haven't been able to do so. could anyone help me with it ?
I've been reading and it looks like I'm violating the single responsibility principle. Any opinions would be more than welcome.
public class RateSystem {
double employeeSalary;
public int salaryRate(String employeePosition) {
if (employeePosition.equalsIgnoreCase("1")) {
return 40;
} else if (employeePosition.equalsIgnoreCase("2")) {
return 30;
} else
employeePosition.equalsIgnoreCase("3");
return 50;
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Employee position please...");
System.out.println("Press 1 for IT " + "\n" + "Press 2 for Tech" +
"\n" + "Press 3 for engineer");
String ePosition = input.nextLine();
RateSystem raul = new RateSystem();
int getPay = raul.salaryRate(ePosition);
System.out.println("How many hours did he work for the week?...");
int weekHours = input.nextInt();
int totalPay = 0;
if (weekHours <= 40) {
totalPay = getPay * weekHours;
System.out.println("Employee salary is " + totalPay);
} else {
int overTimeHours = weekHours - 40;
int extra$$PerOverTime = overTimeHours * getPay +(overTimeHours * getPay/2);
totalPay = getPay * (weekHours - overTimeHours);
System.out.println("The employee accumulated 40 hours equivalent to $"+
totalPay + " plus $" + extra$$PerOverTime + " overtime hours, a total of $"+(extra$$PerOverTime + totalPay));
}
}
}

If we are looking at main(), It does multiple tasks:
Receive user input
Calculate total pay and possible other finance information
Print the results
How's that for starters

I see followings could be added.
1) Salaries are created for Employees so why don't you create and Employee class and encapsulate details inside it like "employeePosition". So you can add more things later and having setters inside it you will get the chance of changing setter logics for employees.
2) You can create a Calculator class and create methods accepting single Employee or a List of Employees and calculate their Salary Rates.
3) You also can add a Printing related class. So you can produce different printing for single or List of Employees or may be like a tabular format.

I have identified following methods in your code.
1) showMainMenu --> responsible to show menu to the user
2) readMenuSelection --> here you will read whatever user has selected in the main menu. It should be read in int value rather than string.
3) For each Selection from menu there will be separate methods such as payForIT(), payForTech() and payForEngineer()

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Employee position please...");
System.out.println("Press 1 for IT " + "\n" + "Press 2 for Tech" + "\n" + "Press 3 for engineer");
String position = input.nextLine();
RateSystem rateSystem = new RateSystem();
rateSystem.setEmployeePosition(position);
System.out.println("How many hours did he work for the week?...");
int weekHours = input.nextInt();
rateSystem.setWeekHours(weekHours);
rateSystem.calculateSalary();
int totalPay = rateSystem.getTotalPay();
int overTime = rateSystem.getOvertime();
if (overTime > 0) {
System.out.println("The employee accumulated 40 hours equivalent to $" + totalPay + " plus $" + overTime
+ " overtime hours, a total of $" + (overTime + totalPay));
} else {
System.out.println("Employee salary is " + totalPay);
}
}
}
public class RateSystem {
private final int STANDARD_WORK = 40;
private double employeeSalary;
private int weekHours;
private Position employeePosition;
private int totalPay = 0;
private int overTime = 0;
public void setEmployeePosition(String position) {
employeePosition = Position.fromString(position);
}
public void setWeekHours(int weekHours) {
this.weekHours = weekHours;
}
public int getTotalPay() {
return totalPay;
}
public int getOvertime() {
return overTime;
}
public void calculateSalary() {
int salaryRate = employeePosition.getRate();
int workhours = (weekHours > STANDARD_WORK) ? STANDARD_WORK : weekHours;
int overTimeHours = (weekHours > STANDARD_WORK) ? (weekHours - STANDARD_WORK) : 0;
totalPay = workhours * weekHours;
overTime = (overTimeHours * salaryRate) + (overTimeHours * salaryRate / 2);
}
}
public enum Position {
IT(40), Tech(30), Engineer(50);
private int rate = 0;
Position(int r) {
rate = r;
}
public int getRate() {
return rate;
}
public static Position fromString(String position) {
switch (position) {
case "1":
return IT;
case "2":
return Tech;
case "3":
return Engineer;
}
return null;
}
}

To follow single responsibility principle you have to create method for each common task in your program. That helps do not repeat code and helps to modify code in one place.
I have created separate methods for building string and for printing string as you use it frequently in your code:
package com.stackoverflow.main;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
println("Employee position please...");
println(buildString("Press 1 for IT ", "\n", "Press 2 for Tech", "\n", "Press 3 for engineer"));
String ePosition = input.nextLine();
RateSystem raul = new RateSystem();
int getPay = raul.salaryRate(ePosition);
println("How many hours did he work for the week?...");
int weekHours = input.nextInt();
int totalPay = 0;
if (weekHours <= 40) {
totalPay = getPay * weekHours;
println(buildString("Employee salary is ", String.valueOf(totalPay)));
} else {
int overTimeHours = weekHours - 40;
int extra$$PerOverTime = overTimeHours * getPay + (overTimeHours * getPay / 2);
totalPay = getPay * (weekHours - overTimeHours);
println(buildString("The employee accumulated 40 hours equivalent to $", String.valueOf(totalPay),
" plus $", String.valueOf(extra$$PerOverTime), " overtime hours, a total of $",
String.valueOf((extra$$PerOverTime + totalPay))));
}
}
private static String buildString(String... strings) {
StringBuilder builder = new StringBuilder();
for (String string : strings) {
builder.append(string);
}
return builder.toString();
}
private static void println(String s) {
System.out.println(s);
}
}
And class RateSystem:
package com.stackoverflow.main;
public class RateSystem {
double employeeSalary;
public int salaryRate(String employeePosition) {
if (equalsIgnoreCase(employeePosition, "1")) {
return 40;
} else if (equalsIgnoreCase(employeePosition, "2")) {
return 30;
} else if (equalsIgnoreCase(employeePosition, "3"))
return 50;
return 0;
}
private boolean equalsIgnoreCase(String arg1, String arg2) {
return arg1.equalsIgnoreCase(arg2);
}
}

Related

Good class organization for a program which is ended or restarted by the user

I have written a small program which calculates total interest, total interest percentage, and other metrics based on a loan amount, rate, and term entered by the user into the console. My question is this: I want the program to compare costs of however many loans the user wants to enter. So, what is the best way to get all my methods to rerun when the user inputs they want to test another loan? Should I use method chaining? Should I have a different class which manages this part of the program? Thanks in advance. The code for the loan program is below.
import java.util.Scanner;
public class loanCalculator implements Comparable<loanCalculator> {
//class variables
double term, rate, amount, monthlyPayment, perRate, totalRepaid,
totalPrincipalRepaid, totalInterestRepaid, totalInterestPercentage;
final double MONTHS_IN_YEAR = 12;
Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
loanCalculator loan = new loanCalculator();
loan.getTerm();
loan.getRate();
loan.getAmount();
loan.setPeriodicInterestRate();
loan.setMonthlyPayment();
loan.setTotalRepaid();
loan.setTotalPrincipalRepaid();
loan.setTotalInterestRepaid();
loan.setTotalInterestPercentage();
System.out.println(loan.toString());
}
void getTerm() {
System.out.println("Enter the term of the loan in years");
this.term = scan.nextDouble();
}
void getRate() {
System.out.println("Enter the rate");
this.rate = scan.nextDouble();
}
void getAmount() {
System.out.println("Enter the amount (no commas or dollar signs");
this.amount = scan.nextDouble();
}
void setPeriodicInterestRate() {
this.perRate = this.rate / 12 /100;
}
void setMonthlyPayment() {
double N = -term*MONTHS_IN_YEAR;
this.monthlyPayment = (perRate * amount) / (1-(Math.pow((1+perRate), N)));
}
void setTotalRepaid() {
this.totalRepaid = term * MONTHS_IN_YEAR * (monthlyPayment);
}
void setTotalPrincipalRepaid() {
this.totalPrincipalRepaid = amount;
}
void setTotalInterestRepaid() {
this.totalInterestRepaid = totalRepaid - totalPrincipalRepaid;
}
void setTotalInterestPercentage() {
totalInterestPercentage = totalInterestRepaid/amount;
}
#Override
public String toString() {
return "Amount: " + amount + "\n" + "Term: " + term + "\n" + "Rate: " + rate +
"\n" + "Monthly Payment: " + monthlyPayment + "\n" + "Total Repaid: " + totalRepaid +
"\n" + "Total Int Repaid: " + totalInterestRepaid + "\n" + "Total Int Percentage: " +
totalInterestPercentage;
}
#Override
public int compareTo(loanCalculator loan1) {
// TODO Auto-generated method stub
if(this.totalInterestPercentage - loan1.totalInterestPercentage > 0) {
return 1;
}
if(this.totalInterestPercentage - loan1.totalInterestPercentage < 0) {
return -1;
}
else if(this.totalInterestPercentage - loan1.totalInterestPercentage ==0) {
return 0;
}
return 0;
}
public void difference(loanCalculator loan1) {
if(this.compareTo(loan1) == 1) {
System.out.print("Loan 2 is cheaper by: " + (this.totalInterestPercentage - loan1.totalInterestPercentage));
}
if(this.compareTo(loan1) == 0) {
System.out.print("The two loans cost the same");
}
else if(this.compareTo(loan1) == 1) {
System.out.print("Loan 1 is cheaper by: " + (this.totalInterestPercentage - loan1.totalInterestPercentage));
}
}
}
(From scratch) Put the code from the main method into a new method:
public static void calculator() {
...
}
Then call calculator() in a loop in main :
while(true) {
calculator();
}
How to terminate ? May like this:
while(true) {
try {
calculator();
} catch (Exception ex) { //scanner will throw an Exception on not valid input
break;
}
}

can not be assigned to a variable error in eclipse (homework)

I am building on a ordering program for java for a class in school and I am getting quantityInput can not be resolved to a variable error I also get the error
the method showInputDialog(Component, Object, Object) in the type JOptionPane is not applicable for the arguments (String, int, int)
any help in resolving the 2 errors would be much aprecated.
/**
* Course: IT110 - Introduction to Programming
* Filename: KagesKreationsPhase1.java
* Created: 04/09/10 by Dr. Debby Telfer
* Modified: 11/26/13 by Dr. Bary W Pollack
*
* Purpose: Created a simple online ordering system
* for Pizzas-R-Us customers
*/
import javax.swing.JOptionPane;
import java.io.*;
import java.util.Scanner;
/**
* #author bary
*/
public class KagesKreations {
/**
* #param args
*/
public static void main(String[] args) {
// declare variables
String openingMsg, nameInputMsg, customerName, nameOutputMsg, getReturning, getColor, getQuantity,
returnInputMsg, customerReturn, returnOutputMsg, quantityMsg, quantityOutputMsg, totalOutputMsg,
colorChoiceMsg, colorChoice, colorChoiceOutputMsg, greetingOutputMsg, outputMsg, quantityInput, getname;
int number = 0;
double cost = 10.00;
double taxRate = 1.07;
double total;
try {
// display opening message
openingMsg = "*** Welcome to Kage's Kreations Online Ordering System ***\n"
+ " Lets Pick A Kustiom Kreation!";
JOptionPane.showMessageDialog(null, openingMsg);
// get required input using dialogs
customerName = getName();
customerReturn = getReturning();
colorChoice = getColor();
quantityInput = getQuantity();
number = Integer.parseInt(quantityInput);
KagesKreations.totalCost(number, cost, taxRate);
total = totalCost(number, cost, taxRate);
writeOrderFile(customerName, customerReturn, colorChoice,quantityInput, total);
confirmation();
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
System.exit(1);
}
} // end main()
public static String getStringInput(String prompt) throws Exception {
String value;
int i = 0;
do {
value = JOptionPane.showInputDialog(prompt);i++;
if (value == null) {
throw new Exception("Cancle was pressed. Closeing the program.");
}
} while (value.equals("") && i < 3);
if (value.equals("")) {
throw new Exception("No input vale was entered after three attempts.");
}
return value;
}
public static int getQuantity(int lowValue, int highValue) throws Exception {
// quantity must be between 1-99
int quantity;
int counter = 0;
int quantityInput;
do {
quantityInput = Integer.parseInt(JOptionPane.showInputDialog("How many bracelets would you like to order? (1-99)", 1, 99));
counter = counter + 1;
} while (quantityInput < lowValue || quantityInput > highValue && counter < 3);
if (quantityInput < lowValue || quantityInput > highValue) {
throw new Exception("Invalid responce please enter a number between 1 and 99");
}
quantity = quantityInput;
return quantity;
}
public static String getColor() throws Exception {
String color;
int counter = 0;
do {
color = JOptionPane.showInputDialog("Please choose Brown or Black for the color of your bracelet");
counter = counter + 1;
} while (!color.equals("Brown") && !color.equals("Black") && counter < 3);
if (!color.equals("Brown") && !color.equals("Black")) {
throw new Exception("Invalid responce please enter Brown or Black.");
}
return color;
}
public static String getReturning() throws Exception {
String returning;
int counter = 0;
do {
returning = JOptionPane.showInputDialog("Are you a returning customer? (Yes or No)");
counter = counter +1;
} while (!returning.equals("Yes") && !returning.equals("No") && counter < 3 );
if (!returning.equals("Yes") && !returning.equals("No")) {
throw new Exception("Invalid responce please enter Yes or No.");
}
return returning;
}
public static String getName() throws Exception {
String name;
int counter = 0;
do {
name = JOptionPane.showInputDialog("Please Enter your name.");
counter = counter + 1;
} while (counter < 3);
return name;
}
public static double totalCost(int number, double cost, double taxRate){
double total = 0;
total = (number * cost) * taxRate;
return total;
}
public static void writeOrderFile(String name, String returning, String color, String quantity, double total) throws Exception {
File order = new File("order.tx");
PrintWriter pw = new PrintWriter(order);
pw.println(name);
pw.println(returning);
pw.println(color);
pw.println(quantity);
pw.println(total);
pw.close();
}
public static void confirmation() throws Exception{
String nameOutputMsg, customerName, returnOutputMsg, customerReturn, colorChoiceOutputMsg, colorChoice, quantityOutputMsg, quantityInput,
totalOutputMsg, total, greetingOutputMsg, outputMsg;
FileReader fr = new FileReader("order.txt");
BufferedReader bf = new BufferedReader(fr);
customerName = bf.readLine();
customerReturn = bf.readLine();
colorChoice = bf.readLine();
quantityInput = bf.readLine();
total = bf.readLine();
fr.close();
// build output strings
nameOutputMsg = "Welcome " + customerName + ".\n\n";
returnOutputMsg = "Your return customer status is " + customerReturn + ".\n";
colorChoiceOutputMsg = "You have chosen " + colorChoice + " as the color for your braclet.\n";
quantityOutputMsg = "You have ordered " + quantityInput + " bracelets.\n";
totalOutputMsg = "Your total cost is $" + total + ".\n";
greetingOutputMsg = "Thank you for visiting Kage's Kreations!" + "\n\n"
+ "Your order should ships in 24 to 48 hours.\n";
// create and display output string
outputMsg = nameOutputMsg + returnOutputMsg + colorChoiceOutputMsg + quantityOutputMsg + totalOutputMsg + greetingOutputMsg;
JOptionPane.showMessageDialog(null, outputMsg);
}
} // end class KagesKreationsPhase1
The second prolem is that JOptionPane just does not provide any method that matches the arguments you try to pass in your getQuantity-mehod:
quantityInput = Integer.parseInt(JOptionPane.showInputDialog("How many bracelets would you like to order? (1-99)", 1, 99));
You have to chose one of the existing methods.
You should declare a variable before using it. You can declare the variable inside the getQuantity() or in class level (Please read much about local and class variables). you can declare it as the way you declared quantity and counter variables.
public static int getQuantity(int lowValue, int highValue) throws Exception {
// quantity must be between 1-99
int quantity;
int counter = 0;
int quantityInput = 0;
...
}
In your code I can't find a place where you are using showInputDialog() with String, int, int parameters. Please share the full code your trying.

I'm trying to do stuff with inheritance but none of it will work

Im trying to get different variables from loan but none of them ever get to loan.java. My inheritance goes from Loan.Java > BusinessLoan.java > CreateLoan.java. I can get a variable from CreateLoan to display in business but when I set it in business I can't grab it. And I know some of this stuff is stupid but this is my final so some of the stuff was required. Heres my code
Loan.java
package Construction;
public class Loan implements LoanConstant{
public static int loanNumber;
public static String lastName;
public static int loanAmount;
public static int interestRate;
public static int term;
public int primeRate;
public int getLoanNumber() { return loanNumber; }
public void setLoanNumber(int n) { n = loanNumber; }
public String getLastName() { return lastName; }
public void setLastName(String s) { s = lastName; }
public int getLoanAmount() { return loanAmount; }
public void setLoanAmount(int n) {
n = loanAmount;
if (loanAmount > MAX_LOAN_AMOUNT)
loanAmount = MAX_LOAN_AMOUNT;
}
public int getTerm() { return term; }
public void setTerm(int n) {
n = term;
if (term == 1) {
term = SHORT_TERM;
} else if (term == 3) {
term = MEDIUM_TERM;
} else if(term == 5) {
term = LONG_TERM;
} else
term = SHORT_TERM;
}
public int getInterestRate() { return interestRate; }
public void setInterestRate(int i) { i = interestRate; }
public static void displayAll() {
System.out.println("The Company's Name is " + COMPANY_NAME);
System.out.println("The loan number is " + loanNumber);
System.out.println("The last name on the loan is " + lastName);
System.out.println("The loan amount is " + loanAmount);
System.out.println("The interest rate on the loan is " + interestRate);
System.out.println("The term on the account is " + term);
}
}
PersonalLoan.java
package Construction;
public class PersonalLoan extends Loan{
public PersonalLoan(int ln, String last, int la, int term) {
setLoanNumber(ln);
setLastName(last);
setLoanAmount(la);
setTerm(term);
interestRate = (int)((primeRate * 0.02) + primeRate);
setInterestRate(interestRate);
}
}
BusinessLoan.java
package Construction;
public class BusinessLoan extends Loan{
public BusinessLoan(int ln, String last, int la, int term) {
setLoanNumber(ln);
setLastName(last);
setLoanAmount(la);
setTerm(term);
interestRate = (int)((primeRate * 0.01) + primeRate);
setInterestRate(interestRate);
}
}
CreateLoan.java
package Construction;
import java.util.Scanner;
public class CreateLoan {
public static void main(String[] args) {
int x = 0;
int primeRate;
String type;
Scanner input = new Scanner(System.in);
Loan[] loans = new Loan[5];
System.out.println("Please enter the prime interest rate");
primeRate = input.nextInt();
primeRate = primeRate/100;
input.nextLine();
for(x = 0; x < 6; ++x) {
System.out.println("Please enter a loan type. Choose either Business or Personal. If you don't type it like that you'll get an error.");
type = input.nextLine();
if (type.equalsIgnoreCase("Business")) {
System.out.println("What is the account number on the loan?");
int ln = input.nextInt();
System.out.println("What is the last name on the account?");
String last = input.nextLine();
input.nextLine();
System.out.println("What is the loan amount? If you put more then 100k it'll only accept up to 100k");
int la = input.nextInt();
System.out.println("What is the term on the account? If you enter something other then 1, 3, or 5 it will default to a short term.");
int term = input.nextInt();
loans[x] = new BusinessLoan(ln, last, la, term);
System.out.println("The Company's Name is " + Loan.COMPANY_NAME);
System.out.println("The loan number is " + loans[x].getLoanNumber());
System.out.println("The last name on the loan is " + loans[x].getLastName());
System.out.println("The loan amount is " + loans[x].getLoanAmount());
System.out.println("The interest rate on the loan is " + loans[x].getInterestRate());
System.out.println("The term on the account is " + loans[x].getTerm());
}
else if (type.equalsIgnoreCase("Personal")) {
System.out.println("What is the account number on the loan?");
int ln = input.nextInt();
System.out.println("What is the last name on the account?");
String last = input.nextLine();
input.nextLine();
System.out.println("What is the loan amount? If you put more then 100k it'll only accept up to 100k");
int la = input.nextInt();
System.out.println("What is the term on the account? If you enter something other then 1, 3, or 5 it will default to a short term.");
int term = input.nextInt();
loans[x] = new PersonalLoan(ln, last, la, term);
System.out.println("The Company's Name is " + Loan.COMPANY_NAME);
System.out.println("The loan number is " + loans[x].getLoanNumber());
System.out.println("The last name on the loan is " + loans[x].getLastName());
System.out.println("The loan amount is " + loans[x].getLoanAmount());
System.out.println("The interest rate on the loan is " + loans[x].getInterestRate());
System.out.println("The term on the account is " + loans[x].getTerm());
} else {
System.out.println("You've entered an invalid type. Please restart and try again.");
System.exit(0);
}
}
}
}
LoanConstants.java
package Construction;
public interface LoanConstant {
public final static int SHORT_TERM = 1;
public final static int MEDIUM_TERM = 3;
public final static int LONG_TERM = 5;
public final static String COMPANY_NAME = "Sanchez Construction";
public final static int MAX_LOAN_AMOUNT = 100000;
}
In addition to the Loan fields being static (remove the static). You should also update your setters.
public void setLoanNumber(int n) { n = loanNumber; }
public void setLastName(String s) { s = lastName; }
You are assigning the value to the passed in variable (not the field). Should be
public void setLoanNumber(int n) { loanNumber = n; }
public void setLastName(String s) { lastName = s; }
and
public void setTerm(int n) {
// n = term;
if (n == 1) {
term = SHORT_TERM;
} else if (n == 3) {
term = MEDIUM_TERM;
} else if (n == 5) {
term = LONG_TERM;
} else
term = SHORT_TERM;
}
public void setInterestRate(int i) { interestRate = i; }

Writing a method for selling Passes, and another Method for selling tickets in JAVA

Hello I am trying to write a code that satisfies the following output:
Here are the booths at the start:
   Ticket booth with 5 passes and 50 tickets
   Ticket booth with 1 passes and 10 tickets
Booth 1 has made $43.0
Booth 2 has made $20.5
Here are the booths at the end:
   Ticket booth with 3 passes and 30 tickets
   Ticket booth with 0 passes and 2 tickets
I was able to do it for the first three lines but I am having trouble writing my methods for sellPass() ,sellTickets() and moneyMade() . Here is the following tester code that is supposed to output my code:
public class TicketBoothTestProgram
{
public static void main(String args[])
{
TicketBooth booth1, booth2;
booth1 = new TicketBooth(5, 50);
booth2 = new TicketBooth(1, 10);
System.out.println("Here are the booths at the start:");
System.out.println(" " + booth1);
System.out.println(" " + booth2);
// Simulate selling 2 passes, 5 tickets, 12 tickets and 3 tickets from booth1
booth1.sellPass();
booth1.sellPass();
booth1.sellTickets(5);
booth1.sellTickets(12);
booth1.sellTickets(3);
// Simulate selling 2 passes, 5 tickets, 12 tickets and 3 tickets from booth2
booth2.sellPass();
booth2.sellPass();
booth2.sellTickets(5);
booth2.sellTickets(12);
booth2.sellTickets(3);
// Make sure that it all worked
System.out.println("\nBooth 1 has made $" + booth1.moneyMade);
System.out.println("Booth 2 has made $" + booth2.moneyMade);
System.out.println("\nHere are the booths at the end:");
System.out.println(" " + booth1);
System.out.println(" " + booth2);
}
}
and here is the code in which I am trying to write my methods:
public class TicketBooth
{
float moneyMade;
int availablePasses;
int availableTickets;
static float TICKET_PRICE = 0.50f;
static float PASS_PRICE = 16.50f;
public TicketBooth()
{
moneyMade = 0.0f;
availablePasses = 0;
availableTickets = 0;
}
public TicketBooth(int p)
{
moneyMade = 0.0f;
availablePasses = p;
availableTickets = 0;
}
public TicketBooth(int p, int t)
{
moneyMade = 0.0f;
availablePasses = p;
availableTickets = t;
}
public String toString()
{
return("Ticket booth with " + this.availablePasses + " passes and " + this.availableTickets +
" tickets");
}
public sellPass()
{
//INSERT CODE HERE FOR SELLING A PASS
}
public sellTickets()
{
//INSERT CODE HERE FOR SELLING A TICKET
}
}
Any help is appreciated thank you!
Your sellPass() method is fairly simple. I have added boolean return types which will retun false if you run out of tickets or passes.
public boolean sellPass() {
//Check if you have a pass to sell
if (availablePasses > 0) {
//you have passes to sell
moneyMade += moneyPerPass; // add the money
availablePass--; //decrement pass counter
return true;
}
return false; // not enough passes to sell
}
Same way your sellTickets(int noOfTickets), your method should allow how many tickets you want to sell.
public boolean sellTickets(int noOfTickets) {
if(availableTickets >= noOfTickets) {
moneyMade += noOfTickets * pricePerTicket;
availableTickets -= noOfTickets;
return true;
}
return false;
}

Java - Calling methods from other classes with calculated fields

So I've been looking at this piece of code all afternoon and I can't see the error(s). Here is what I'm supposed to do:
Create a Delivery class for a delivery service. The class contains fields to hold the following:
A delivery number that contains eight digits. The first four digits represent the year, and the last four digits represent the delivery number.
A code representing the delivery area. A local delivery is code 1, and a long distance delivery is code 2.
A weight, in pounds, of the item to be delivered.
The fee for the delivery, as follows:
Create a constructor for the Delivery class that accepts arguments for the year,
delivery number within the year, delivery distance code, and weight of the package. The
constructor determines the eight-digit delivery number and delivery fee. Also include a
method that displays every Delivery object field. Save the file as Delivery.java.
Next, create an application that prompts the user for data for a delivery. Keep
prompting the user for each of the following values until they are valid:
A four-digit year between 2001 and 2025 inclusive
A delivery number for the year between 1 and 9999 inclusive
A package weight between 0.10 pound and 100 pounds inclusive
A delivery distance code that is either 1 or 2
When all the data entries are valid, construct a Delivery object, and then display its
values. Save the file as CreateDelivery.java.
So here is my delivery Class
import javax.swing.*;
import java.util.*;
class Delivery
{
//variables
private int year;
private int deliveryNumber; //deliveryNo
private double weight;
private int distanceCode; //code
//constructor
//Delivery()
//{
// year = year;
// deliveryNumber = deliveryNumber;
// weight = weight;
// distanceCode = distanceCode;
//}
//get year
public int getYear()
{
return year;
}
//set year
public int setYear (int newYear)
{
year = newYear;
return year;
}
//get deliveryNumber
public int getDeliveryNumber()
{
return deliveryNumber;
}
//set deliveryNumber
public int setDeliveryNumber (int newDeliveryNumber)
{
deliveryNumber = newDeliveryNumber;
return deliveryNumber;
}
//get weight
public double getWeight()
{
return weight;
}
//set Weight
public double setWeight (double newWeight)
{
weight = newWeight;
return weight;
}
//get distanceCode
public int getDistanceCode()
{
return distanceCode;
}
//set distanceCode
public int setDistanceCode (int newDistanceCode)
{
distanceCode = newDistanceCode;
return distanceCode;
}
//calculate fee
public double displayFees(int distance, double w) //distance = c
{
double fees = 0;
if(distance == 1)
{
if(w < 5)
{
fees = 12;
}
else if((w < 20)&&(w > 5))
{
fees = 16.50;
}
else if(w > 20)
{
fees = 22;
}
}
else if(distance == 2)
{
if(w < 5)
{
fees = 35;
}
else if(w >= 5)
{
fees = 47.95;
}
}
return fees;
}
//display method
public void display(int year, int deliveryNumber, double weight, int distanceCode)
{
System.out.println("Year: " + year + '\n'
+ "Delivery Number: " + deliveryNumber + '\n'
+ "Weight of the package: " + weight + '\n'
+ "Delivery code: " + distanceCode);
}
}
And here is my CreateDelivery Class
import javax.swing.JOptionPane;
import java.util.Scanner;
public class CreateDelivery
{
public static void main(String []args)
{
Delivery delivery1 = new Delivery();
//scanner year
Scanner input = new Scanner(System.in);
System.out.print("Please enter the current year, format (yyyy) >>> ");
delivery1.setYear(input.nextInt());
//loop year
while((delivery1.getYear() <= 2000)||(delivery1.getYear() >= 2026))
{
System.out.println('\n'+ "Error, year should be in the range of (2010 - 2025). Please enter a valid option >> ");
delivery1.setYear(input.nextInt());
}
//scanner for delivery number
System.out.print('\n'+ "Please enter a delivery number: ");
delivery1.setDeliveryNumber(input.nextInt());
//loop for delivery number
while((delivery1.getDeliveryNumber() <= 0001)||(delivery1.getDeliveryNumber() >= 10000))
{
System.out.println("Error, the delivery number is a 4 digit number between 0001 and 9999, please enter a valid option >> ");
delivery1.setDeliveryNumber(input.nextInt());
}
//scanner for weight
System.out.print("Please enter the weight of the package (in pounds): ");
delivery1.setWeight(input.nextDouble());
//loop for weight
while((delivery1.getWeight() <= .09)||(delivery1.getWeight() >= 101))
{
System.out.println("Error, the minimum allowed weight is 0.10 pounds and the maximum is 100 pounds. Please enter a valid weight >> ");
delivery1.setWeight(input.nextDouble());
}
//scanner for delivery code
System.out.print("Please enter 1 for local or 2 for long distance deliveries >> ");
delivery1.setDistanceCode(input.nextInt());
//loop for delivery code
while((delivery1.getDistanceCode() == 1) && (delivery1.getDistanceCode() == 2))
{
System.out.println("Error, please enter a valid distance code (1 for local deliveries and 2 for long distance deliveries) >> ");
delivery1.setDistanceCode(input.nextInt());
}
//turn int to string
String n = Integer.toString(delivery1.getDeliveryNumber());
String y = Integer.toString(delivery1.getYear());
String trackingNumber = n + y;
System.out.println(delivery1.getDistanceCode() + " "
+ trackingNumber + " " + delivery1.getWeight() + " " + fees);
}
}
So I made the changes you guys suggested, but now I can't pull fees from the Delivery class. Any thoughts?
Delivery()
{
year = year;
deliveryNumber = deliveryNumber;
weight = weight;
distanceCode = distanceCode;
}
Replace it with something along the lines of:
Delivery(int year, int deliveryNumber, int weight, int distanceCode)
{
this.year = year;
this.deliveryNumber = deliveryNumber;
this.weight = weight;
this.distanceCode = distanceCode;
}
From there, I would avoid using the set methods. Instead, store all the values into respective fields as you load them from the System.in. Once you have all the fields, create the Delivery object.
I think you are missing () at the end of the methods such as getDeliveryNumber,getYear etc. in the while loop.
and you are also using undeclared variables at the end such as getDeliveryNumber,getYear etc.
or we can do that simply like Delivery class
public class Delivery {
private int year,deliveryNumber,distanceCode;
private double weight;
private double fees=0;
//delivery class constructor
public Delivery(int year,int deliveryNumber,int distanceCode,double weight)
{
this.year=year;
this.deliveryNumber=deliveryNumber;
this.distanceCode=distanceCode;
this.weight=weight;
}
//calculate delivery fee
public void displayFees(int distanceCode, double weight)
{
if(distanceCode == 1)
{
if(weight<5)
{
fees = 12;
}
else if((weight < 20)&&(weight >=5))
{
fees = 16.50;
}
else if(weight > 20)
{
fees = 22;
}
}
else if(distanceCode == 2)
{
if(weight <5)
{
fees = 35;
}
else if(weight >= 5)
{
fees = 47.95;
}
}
}
public double getFee()
{
return fees;
}
}
and CreateDelivery class:
public class CreateDelivery {
public static void main(String[] args) {
int year=(int)ReadValues.readValue("Year", 1999,2026);
int deliveryNumber=(int)ReadValues.readValue("Delivery Number (1 to 10000)", 0,10000);
int distanceCode=(int)ReadValues.readValue("DistanceCode (1 or 2)",0, 3);
double weight=ReadValues.readValue("weight",0, 20);
Delivery delivery=new Delivery(year, deliveryNumber, distanceCode, weight);
delivery.displayFees(distanceCode, weight);
double fee=delivery.getFee();
System.out.println("\n\n*****Delivery Fees Details*****\n\nTrackingNumber:"+year+deliveryNumber+"\nDistanceCode:"+distanceCode+"\nFee :"+fee);
}
}
and for reading values from user another class called ReadValue
import java.util.Scanner;
public class ReadValues {
public static double readValue(String prompt, int min, int max) {
Scanner scan = new Scanner(System.in);
double value;
System.out.print(prompt + " :");
while (true) {
value = scan.nextDouble();
if (value < min || value > max)
System.out.println("Enter value between " + min + " & " + max);
else
break;
}
return value;
}
}

Categories

Resources