Outputting information using super and overwriting - java

I am trying to get the right total sales output, I keep on getting 0.0 instead of the appropriate 400 and 950 for the first and second employee.
I think my problem is in the Commission class with the overwritten pay method
The overridden pay method in Commission must call the pay method from the parent class from Hourly to compute the pay for hours worked then add to that the pay from commission on sales(totals sales times the commission rate) The total sales should be reset to 0 after the payment is calculated. –
public class Commission extends Hourly
{
double total_sales;
double commission_rate;
public Commission(String name, String address, String phone,
String soc_sec_number, double rate,double commission_rate)
{
super( name, address, phone,
soc_sec_number, rate);
// set commission rate
commission_rate = 0.02;
}
public void addSales (double sales)
{
total_sales += sales;
}
public double pay()
{
double payment = super.pay(); // call the method of the parent
// add other code
payment = payment + (total_sales * commission_rate);
total_sales = 0.0;
return payment;
}
public String toString()
{
return super.toString() + "\nTotalSales: " + total_sales;
}
}
Hourly, the parent class with the pay method
// ********************************************************************
// Hourly.java Java Foundations
//
// Represents an employee that gets paid by the hour
// ********************************************************************
public class Hourly extends Employee
{
private int hours_worked;
// -------------------------------------------------------------------------
// Constructor: Sets up this hourly employee using the specified information
// -------------------------------------------------------------------------
public Hourly(String name, String address, String phone,
String soc_sec_number, double rate)
{
super(name, address, phone, soc_sec_number, rate);
hours_worked = 0;
}
// -----------------------------------------------------
// Adds the specified number of hours to this employee's
// accumulated hours
// -----------------------------------------------------
public void addHours(int more_hours)
{
hours_worked += more_hours;
}
// -----------------------------------------------------
// Computes and returns the pay for this hourly employee
// -----------------------------------------------------
public double pay()
{
double payment = pay_rate * hours_worked;
hours_worked = 0;
return payment;
}
// ----------------------------------------------------------
// Returns information about this hourly employee as a string
// ----------------------------------------------------------
public String toString()
{
return super.toString() + "\nCurrent hours: " + hours_worked;
}
}
and staff where all the information is stored
// ********************************************************************
// Staff.java Java Foundations
//
// Represents the personnel staff of a particular business
// ********************************************************************
import java.text.DecimalFormat;
public class Staff
{
private static DecimalFormat fmt = new DecimalFormat("0.00");
private StaffMember[] staff_list =
{
new Executive ("Tony", "123 Main Line", "555-0469", "123-45-6789", 2423.07),
new Employee ("Paulie", "456 Off Line", "555-0101", "987-65-4321", 1246.15),
new Employee ("Vito", "789 Off Rocker", "555-0000", "010-20-3040", 1169.23),
new Hourly ("Michael", "678 Fifth Ave.", "555-0690", "958-47-3625", 10.55),
new Volunteer ("Adrianna", "987 Babe Blvd.", "555-8374"),
new Volunteer ("Benny", "321 Dud Lane", "555-7282"),
new Commission("Christopher", "345 Movie Lane", "555-3831", "302-48-3871", 6.25, 0.2),
new Commission("Bobby", "61 Train St.", "555-2869", "492-58-2956", 9.75, 0.15)
};
// ----------------------------------
// Constructor: Updates staff members
// ----------------------------------
public Staff()
{
((Executive)staff_list[0]).awardBonus(500.00);
((Hourly)staff_list[3]).addHours(40);
((Commission)staff_list[6]).addHours(35); // add commissioned employees
((Commission)staff_list[7]).addHours(40);
}
// ----------------------
// Pays all staff members
// ----------------------
public void payday()
{
double amount;
for (int count=0; count < staff_list.length; count++)
{
System.out.println(staff_list[count]);
amount = staff_list[count].pay();
if (amount == 0.0)
System.out.println("Thanks!");
else
System.out.println("Paid: " + fmt.format(amount));
System.out.println("-----------------------------------");
}
}
}

First of all, I don't see your field total_sales being initialized in your Commission constructor.
Also, I am not sure what you mean by first and second employee, if you are referring to staff_list[1] and staff_list[2] they are Employee class so verify that the Employee constructor is being properly initialized, the only way I see them earning any money is if they have some hard-coded number being returned in the Employee.pay() method.

Related

Java inheritance / overriding method ISSUE

okay so to the preface the situation. I have been given an assignment with various tasks. So far I have created a Canteen Account(which will be shown below), a main menu class, and now I have to make another class which inherits from Canteen Account, called StaffAccount. A StaffAccount object should contain the following additional property :
discountRate - the rate (percentage) discount applied to all purchases
A StaffAccount object should contain the following additional methods:
(i) StaffAccount (String newId, String newName, double discountRate)
A constructor method to initialise the StaffAccount object’s properties via the three parameters.
In the staff account I am having issues with a method called PayForMeal(which is an overridden method) which in the assignment brief has the purpose of:
A method to record the cost of a meal. The balance on a StaffAccount object should be amended to reflect discount on the cost of a meal (if the cost does not exceed available balance).
If the cost exceeds the balance then an Exception will be thrown to warn the customer they must topUp their balance – if the customer is within their credit limit a negative value will be recorded in the balance and the status of the account changed to show that the customer is using credit.
No discount should be applied if the customer is using credit.
So my issue is, how do I make a staff account using the constructor given to me, and then use the payForMeal overridden method to apply a discount to the amount a meal costs, then take the discounted amount away from a balance which is not there because it is not in the constructor for the StaffAccount, but it is in the constructor for the CanteenAccount. The classes are below, i just want to know if this is possible or am I being dumb
//////CANTEEN ACCOUNT \\\\\\\\
public class CanteenAcc
{
private String customerId;
private String name;
private double balance;
private static double minTopup = 2.00;
private String status;
private static double creditLimit = 5.00;
private static int transCount;
/**
* Constructor to create a Canteen account object using three parameters
* #param newId - String
* #param newName - String
* #param newBalance - Double
*/
public CanteenAcc(String newId, String newName, double newBalance)
{
this.customerId = newId;
this.name = newName;
this.balance = newBalance;
}
public CanteenAcc(String newId, String newName)
{
this.customerId = newId;
this.name = newName;
}
//BEFORE EVERY METHOD AND CLASS YOU SHOULD HAVE JAVADOC COMMENTS.
public void topUp(double depositAmount)
{
if(depositAmount > 0)
{
this.balance += depositAmount;
this.status = "Valid";
}else
{
this.status = "Invalid";
}
}
public void payForMeal(double amount) throws Exception
{
if(balance - amount < 0 && amount - balance <= creditLimit)
{
this.status = "Using Credit";
double newBalance = balance - amount;
balance = newBalance;
throw new Exception("\n\n-----------------------------\n"
+ "You must top-up your balance\n"
+ "Your new balance is: "+ balance + " GBP" +"\n"
+ "You are: " + status + "\n"
+ "-----------------------------\n");
}
else if(amount > creditLimit && balance < amount)
{
throw new Exception("\n\n------------------------------\n"
+ "Cost exceeds the credit limit."
+ "\n------------------------------\n");
}
else
{
double newBalance = balance - amount;
balance = newBalance;
transCount++;
}
}
public String displayAccountDetails()
{
StringBuilder ad = new StringBuilder();
ad.append("------------------------\n");
ad.append("****Account Details****\n");
ad.append("------------------------\n");
ad.append("\n");
ad.append("****Customer ID****: \n" + customerId + "\n");
ad.append("\n");
ad.append("****Name****: \n" + name + "\n");
ad.append("------------------------\n");
ad.append("\n");
return ad.toString();
}
public String getStatistics()
{
StringBuilder as = new StringBuilder();
as.append("------------------------\n");
as.append(" CANTEEN ACCOUNT \n");
as.append("------------------------\n");
as.append("\n");
as.append("****Transaction Count****\n");
as.append(transCount + "\n");
as.append("\n");
as.append("****Account Balance****\n");
as.append(balance + "\n");
as.append("\n");
as.append("***Account Status****\n");
as.append(status + "\n");
as.append("------------------------\n");
return as.toString();
}
public double getBalance()
{
return balance;
}
public double getCreditLimt()
{
return creditLimit;
}
public double getMinTopup()
{
return minTopup;
}
public String getStatus()
{
return status;
}
public static void updateCreditLimit(double newLimit)
{
creditLimit = newLimit;
}
public static void updateMinTopup(double newTopup)
{
minTopup = newTopup;
}
}
////////MAIN METHOD////////////////////////
public class Test
{
public static void main(String[] args) {
String menuItems[] = {"1. Top up account ", "2. Pay for meal ", "3. Display Account Status",
"4. Display Account Balance ", "5. Display Account Details ",
"6. Update credit limit ", "7. Update Minimum top-up ", "8. Exit program"};
Menu myMenu = new Menu("Holiday Account", menuItems) ;
int choice;
Scanner keyb = new Scanner(System.in);
choice = myMenu.getChoice() ;
do{
choice = myMenu.getChoice();
//CanteenAcc Employee = new CanteenAcc("A01PL", "Patrick", 2);
CanteenAcc Employee2 = new StaffAccount("blah", "blah", 0.25);
switch (choice)
{
case 1 : System.out.println("How much would you like to top-up: ");
double deposit = keyb.nextDouble();
Employee2.topUp(deposit);
System.out.println("Your balance is: £" + Employee2.getBalance());
break ;
case 2: System.out.println("Input how much your meal costs: ");
try {
double amount = keyb.nextDouble();
Employee2.payForMeal(amount);
System.out.println("Your meal cost: " + amount);
} catch(Exception ex)
{
System.out.println(ex.toString());
}
System.out.println("Your balance is: £" + Employee2.getBalance());
break ;
case 3: System.out.println(Employee2.getStatus());
break;
case 4: System.out.println("£" + Employee2.getBalance());
break;
case 5: System.out.println(Employee.displayAccountDetails());
break;
case 6: System.out.println("What amount would you like the new limit to be: ");
double newLimit = keyb.nextDouble();
CanteenAcc.updateCreditLimit(newLimit);
System.out.println("The new credit limit is: " + newLimit);
case 7: System.out.println("What amount would you like the new limit to be: ");
double newMinTopup = keyb.nextDouble();
CanteenAcc.updateMinTopup(newMinTopup);
System.out.println("The new minimum topUp is: " + newMinTopup);
case 8: System.exit(0);
}
}//End DoWhile
while(choice != 8);
}
}
////STAFF ACCOUNT///////
public class StaffAccount extends CanteenAcc
{
private double discountRate;
public StaffAccount(String newId, String newName, double discountRate)
{
super (newId, newName);
this.discountRate = 0.25;
balance = 0;
}
public void setDiscountRate(double rate)
{
discountRate = rate;
}
public double getDiscountRate()
{
return discountRate;
}
public void payForMeal(double amount) throws Exception
{
amount = amount/discountRate;
super.payForMeal(amount);
}
}
OK:
You've got a CanteenAcc: good. You've also got a StaffAccount that inherits from CanteenAcc. Also good.
You should annotate StaffAccount.payForMeal() with #Override: When do you use Java's #Override annotation and why?
Your variable names should all start with lower case, e.g. CanteenAcc employee2 = new StaffAccount("blah", "blah", 0.25);.
updateCreditLimit() and updateMinTopup() should NOT be static (because each different object might have a different value): Java: when to use static methods
... Finally ...
With CanteenAcc employee = new CanteenAcc("A01PL", "Patrick", 2);, then employee.payForMeal() will have the "CanteenAcc" behavior.
With CanteenAcc employee2 = new StaffAccount("blah", "blah", 0.25);, then employee2.payForMeal() will have the "StaffAccount" behavior.
Q: So what's the problem? Does that help clarify ... or does it just confuse things further?
There are a number of things "wrong" with the code you posted. I hope you have an IDE, and step through the debugger with sample test values.
But to your original question:
You're on the right track.
There are a couple of "minor" issues I noted above.
I'm not sure why you're worried about "constructors". The way object oriented languages (like Java) work - if you define the right base classes, and appropriately "specialize" behavior in subclasses, then - through the magic of "inheritence" - everything "just works".
I modified your code slightly, and wrote a different "test driver". Here is the code, and the output:
StaffAccount.java
package com.example;
public class StaffAccount extends CanteenAccount {
private double discountRate;
public StaffAccount(String newId, String newName, double discountRate) {
super(newId, newName);
this.discountRate = discountRate; // Set this to "discountRate", instead of hard-coding 0.25
// You'll note that "balance" is implicitly set to "0.0" in the base class
}
public void setDiscountRate(double rate) {
discountRate = rate;
}
public double getDiscountRate() {
return discountRate;
}
#Override
public void payForMeal(double amount) throws Exception {
amount = amount / discountRate;
super.payForMeal(amount);
}
}
TestAccount.java
package com.example;
/**
* Test driver
* In a "real" application, I would implement these as a suite of JUnit tests
*/
public class TestAccount {
private static void buyAMeal (CanteenAccount person, double cost) {
try {
person.payForMeal(cost);
} catch (Exception e) {
System.out.println ("ERROR: " + e.getMessage());
}
}
public static void main(String[] args) {
System.out.println (">>Creating employee (\"CanteenAccount\" and employee2 (\"StaffAccount\") objects...");
CanteenAccount employee = new CanteenAccount("A01PL", "Patrick", 2);
CanteenAccount employee2 = new StaffAccount("blah", "blah", 0.25);
System.out.println (">>Checking initial balances...");
System.out.println (" employee balance=" + employee.getBalance() + ", creditLimit=" + employee.getCreditLimit());
System.out.println (" employee2 balance=" + employee2.getBalance() + ", creditLimit=" + employee2.getCreditLimit());
System.out.println (">>Buying a $5.00 meal...");
System.out.println (" employee...");
buyAMeal (employee, 5.00);
System.out.println (" employee balance=" + employee.getBalance() + ", creditLimit=" + employee.getCreditLimit());
System.out.println (" employee2...");
buyAMeal (employee2, 5.00);
System.out.println (" employee2 balance=" + employee2.getBalance() + ", creditLimit=" + employee2.getCreditLimit());
System.out.println (">>Add $5.00 and buy another $5.00 meal...");
System.out.println (" employee...");
employee.topUp(5.0);
buyAMeal (employee, 5.00);
System.out.println (" employee balance=" + employee.getBalance() + ", creditLimit=" + employee.getCreditLimit());
System.out.println (" employee2...");
employee2.topUp(5.0);
buyAMeal (employee2, 5.00);
System.out.println (" employee2 balance=" + employee2.getBalance() + ", creditLimit=" + employee2.getCreditLimit());
}
}
Sample output:
>>Creating employee ("CanteenAccount" and employee2 ("StaffAccount") objects...
>>Checking initial balances...
employee balance=2.0, creditLimit=5.0
employee2 balance=0.0, creditLimit=5.0
>>Buying a $5.00 meal...
employee...
ERROR:
-----------------------------
You must top-up your balance
Your new balance is: -3.0 GBP
You are: Using Credit
-----------------------------
employee balance=-3.0, creditLimit=5.0
employee2...
ERROR:
------------------------------
Cost exceeds the credit limit.
------------------------------
employee2 balance=0.0, creditLimit=5.0
>>Add $5.00 and buy another $5.00 meal...
employee...
ERROR:
-----------------------------
You must top-up your balance
Your new balance is: -3.0 GBP
You are: Using Credit
-----------------------------
employee balance=-3.0, creditLimit=5.0
employee2...
ERROR:
------------------------------
Cost exceeds the credit limit.
------------------------------
employee2 balance=5.0, creditLimit=5.0

Object oriented programming, getter is not getting private variable from another class

The program is supposed to calculate interest for 2 accounts after 12 and 24 months. This works fine. My issue is the getter/setter for interest rate do not work, so when the interest rate is saved as 0.1 in another class private variable I can't print it from main class.
public class testAccountIntrest{
//main method
public static void main(String[] args) {
//creating objects
Account account1 = new Account(500);
Account account2 = new Account(100);
//printing data
System.out.println("");
System.out.println("The intrest paid on account 1 after 12 months is " + account1.computeIntrest(12));
System.out.println("");
System.out.println("The intrest paid on account 1 after 24 months is " + account1.computeIntrest(24));
System.out.println("");
System.out.println("");
System.out.println("The intrest paid on account 2 after 12 months is " + account2.computeIntrest(12));
System.out.println("");
System.out.println("The intrest paid on account 2 after 24 months is " + account2.computeIntrest(24));
System.out.println("");
System.out.println("The intrest rate is " + getIntrest());
}//end main method
}//end main class
class Account {
//instance variables
private double balance;
private double intrestRate = 0.1;
//constructor
public Account(double initialBalance) {
balance = initialBalance;
}
//instance methods
public void withdraw(double amount) {
balance -= amount;
}
public void deposit(double amount) {
balance += amount;
}
public double getBalance() {
return balance;
}
public void setIntrest(double rate) {
intrestRate = rate;
}
public double getIntrest() {
return intrestRate;
}
public int computeIntrest(int n) {
double intrest = balance*Math.pow((1+intrestRate),(n/12));
return (int)intrest;
}
}
As the compiler is undoubtedly telling you, your testAccountIntrest class doesn't have a method called getInterest(). So this alone can't do anything in the context of that class:
getInterest()
However, your Account class does have that method. And you have two Account objects in that scope:
Account account1 = new Account(500);
Account account2 = new Account(100);
So you can call that method on those objects:
account1.getInterest()
or:
account2.getInterest()
Basically, you have to tell the code which object you're calling the method on. It can't figure it out on its own.
getIntrest() is a member method, therefore you need to call
System.out.println("The intrest rate for account 1 is " + account1.getIntrest());
System.out.println("The intrest rate for account 2 is " + account2.getIntrest());
To call a method from another class you need an object of another class.
So, you need an instance of account to call getIntrest. For example:
System.out.println("The intrest rate for account 1 is " + account1.getIntrest());
If an interest rate is the same for all accounts you can make it static:
private static double intrestRate = 0.1;
public static double getIntrest() {
return intrestRate;
}
Static fields belong to the class and you don't need a specific instance to access it:
System.out.println("The intrest rate for all accounts is " + Account.getIntrest());

Import data in file and use to compute salary [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Working on a java program that computes salaries for a collection of employees of different types, which is imported from a TXT file.
The program builds and runs successfully if I comment out:
System.out.println("\nAverage Salary for 2014: " + (totalSalary / indexYear2014));
System.out.println("\nAverage Salary for 2015: " + (totalSalary / indexYear2015));
However, it does not seem that the data is imported/used at all.
Here is the full code:
package computeemployeesalary;
/**
*
* #author Jason Snook
* Course name: Intermediate Programming (CMIS 242)
* Assignment: Project 1 - Compute Employee Salary
*/
/**
* This program computes the salaries of a collection of employees of
* different types: Employee, Salesman, Executive
*
* Salary for employee is calculated by multiplying monthly salary by 12
*
* Salary for salesman takes the base of employee, and then adds commission,
* which has a cap of 20000
*
* Salary for executive takes the base of employee, and then adds a bonus
* in the event that the current stock is more than 100
*/
// Imports
import java.util.Scanner;
import java.io.*;
/**
* This class contains the employee name and monthly salary
*/
// Employee class
class Employee {
// Variable declaration
String employeeName;
int monthlySalary = 0;
// Employee constructor
public Employee(String employeeName, int monthlySalary) {
this.employeeName = employeeName;
this.monthlySalary = monthlySalary;
} // end Employee constructor method
// Calculate employee annual salary
public int annualSalary() {
return monthlySalary * 12;
} // end annualSalary method
// Return employee name and annual salary as String
#Override // takes advantage from compiler checking
public String toString() {
return "Employee Name: " + employeeName +
" Salary: $" + monthlySalary;
} // end toString method
} // end employee class
/**
* This class contains the salesman annual sales and extends employee class
*/
// Salesman subclass, extends Employee class
class Salesman extends Employee {
// Variable declaration
int annualSales = 0;
// Salesman constructor
public Salesman(String employeeName, int monthlySalary, int annualSales) {
super(employeeName, monthlySalary);
this.annualSales = annualSales;
} // end Salesman constructor method
#Override // takes advantage from compiler checking
// Computes commission and annual salary
public int annualSalary() {
int commission = annualSales * 3 / 100;
// if commission is greater than 25000, then set commission to 25000
if (commission > 25000) {
commission = 25000;
} // emd comission if
return (monthlySalary * 12 + commission);
} // end annualSalary method
#Override // takes advantage from compiler checking
// Displays output details as String
public String toString(){
return "Employee Name: " + employeeName +
" Salary: $" + monthlySalary;
} // end toString method
} // end Salesman class
/**
* This class contains the current stock price and extends employee class
*/
// Executive subclass, extends Employee class
class Executive extends Employee {
// Variable declaration
int currentStockPrice = 0;
// Executive constructor
public Executive(String employeeName,
int monthlySalary, int currentStockPrice) {
super(employeeName, monthlySalary);
this.currentStockPrice = currentStockPrice;
} // end Executive constructor method
#Override // takes advantage from compiler checking
// Computes commission and annual salary
public int annualSalary() {
int executiveBonus = 0;
// Adds executive bonus if stock is greater than 100
if(currentStockPrice > 100) {
executiveBonus = 20000;
} // end executiveBonus if
return (monthlySalary * 12 + executiveBonus);
} // end annualSalary method
#Override // takes advantage from compiler checking
// Displays output details as String
public String toString() {
return "Employee Name: " + employeeName +
" Salary: $" + monthlySalary;
} // end toString method
} // end Executive class
/**
* This class computes salary based on input file and reports results
*/
public class ComputeEmployeeSalary {
// Main method
public static void main(String[] args) throws IOException {
// Import text file and compute salary increase
try {
// Create a File instance
java.io.File file = new java.io.File("employees.txt");
// Create Scanner object
Scanner input = new Scanner(file);
// Create arrays for 2014 and 2015
Employee year2014[] = new Employee[20];
Employee year2015[] = new Employee[20];
// Create indexes for 2014 and 2015 arrays
int indexYear2014 = 0, indexYear2015 = 0;
// Read data from a file
while (input.hasNext()) {
String year = input.next();
String employeeTitle = input.next();
String employeeName = input.next();
int monthlySalary = input.nextInt();
// Action if employee is a regular employee.
if (employeeTitle.equalsIgnoreCase("Employee")) {
Employee regularEmployee = new Employee(employeeName,
monthlySalary);
if (year == "2014") {
year2014[indexYear2014++] = regularEmployee;
} // end 2014 if
if (year == "2015") {
year2015[indexYear2015++] = regularEmployee;
} // end 2015 if
} // end Employee if
// Action if employee is a salesman.
if (employeeTitle.equalsIgnoreCase("Salesman")){
int annualSales = input.nextInt();
Salesman salesEmployee = new Salesman(employeeName,
monthlySalary, annualSales);
if (year == "2014") {
year2014[indexYear2014++] = salesEmployee;
} // end 2014 if
if (year == "2015") {
year2015[indexYear2015++] = salesEmployee;
} // end 2015 if
} // end Salesman if
// Action if employee is an executive.
if (employeeTitle.equalsIgnoreCase("Executive")) {
int currentStockPrice = input.nextInt();
Executive executiveEmployee = new Executive(employeeName,
monthlySalary, currentStockPrice);
if (year == "2014") {
year2014[indexYear2014++] = executiveEmployee;
} // end 2014 if
if (year == "2015") {
year2015[indexYear2015++] = executiveEmployee;
} // end 2015 if
} // end Executive if
} // end While
// Generate Report for 2014
int totalSalary = 0;
System.out.println("===== Salary Report for 2014 =====");
for (int i = 0; i < indexYear2014; i++) {
System.out.print(year2014[i]);
System.out.println(" Annual Salary: " +
year2014[i].annualSalary());
} // end annualSalary 2014 for
for (int i = 0; i < indexYear2014; i++) {
totalSalary+= year2014[i].annualSalary();
} // end totalSalary 2014 for
System.out.println("\nAverage Salary for 2014: " +
(totalSalary / indexYear2014));
// Generate Report for 2015
System.out.println("\n===== Salary Report for 2015 =====");
for (int i = 0; i < indexYear2015; i++) {
System.out.print(year2015[i]);
System.out.println(" Annual Salary: " +
year2015[i].annualSalary());
} // end annualSalary 2015 for
for (int i = 0; i < indexYear2015; i++) {
totalSalary+= year2015[i].annualSalary();
} // end totalSalary 2015 for
System.out.println("\nAverage Salary for 2015: " +
(totalSalary / indexYear2015));
// Close input file
input.close();
} // end try
catch (IOException i) {
System.out.println("Error: File Not Found, error code: " + i);
} // end catch
} // end main method
} // end ComputeEmployeeSalary class
Any help would be greatly appreciated.
The reason it works when you comment out those 2 lines is that they cause a divide by zero error. Both indexYear2014 and indexYear2015 are 0.
The reason for this is the way you're comparing Strings:
year == "2015" should be year.equals("2015")

How to get the calculation results to print - Java

So what this program is suppose to do is grab input from the keyboard for the id, hours and wage. It is then going to calculate the overtime pay, regular pay and gross pay. After the calculations, id, hours, wage, overtime pay, regular pay and gross pay are supposed to be calculated have to be printed to the output.
Also the properties and the behaviours of the employee are suppose to be in the employee class.
But when I want to print the toString method, Regular Pay, Overtime pay and gross pay comes out as zeros. Any idea why?
main method:
public class FinalExam
{ // begin class
public static void main(String[] args)
{ // begin main
// ********** DECLARATION OF CONSTANTS **********
// ********** DECLARATION OF VARIABLES **********
String strout; // output string (toString)
int ID; // employee's id number
int Hours; // employee's hours worked
double Wage; // employee's wage per hour
// ********** CREATE OBJECTS **********
ArrayList<Employee> employeeInfo = new ArrayList(); // list of all employee's properties/objects
// ********** CREATE INPUT STREAMS **********
Scanner keyboard = new Scanner(System.in); // create a Scanner object for keyboard input.
// ********** GET INPUT **********
// get the employee's ID
System.out.println("\nEnter your employee ID.");
ID = keyboard.nextInt(); //get the input and set it to the local varaible ID
Employee employee = new Employee(ID); // pass your id
//System.out.println("Employee ID: " + ID);
// get the employee's hours worked
System.out.println("\nEnter the amount of hours you worked this week.");
Hours = keyboard.nextInt(); //get the input and set it to the local varaible HoursWorked
employee.setHours(Hours); // pass your hours
//System.out.println("Hours worked: " + Hours);
// get the employee's wage
System.out.println("\nEnter your wage.");
Wage = keyboard.nextDouble(); //get the input and set it to the local varaible Wage
employee.setWage(Wage); // pass your wage
//System.out.println("Employee wage: " + Wage);
employeeInfo.add(employee); // add it to the list of course
// ********** OUTPUT **********
System.out.println("\n\n" + employeeInfo.toString());
} // end main
} // end class
then the Employee class:
public class Employee
{ // begin class
// *********** CLASS VARIABLES **********
// *********** CLASS CONSTANTS **********
private static int MAXHOURS = 40; // maximum hours before overime
private static double OTRATE = 1.5; // overtime is one and a half
// ********** INSTANCE VARIABLES **********
private int ID; // employee's id
private int Hours; // number of hours worked
private double Wage; // pay per hour
private double RegularPay; // regular pay
private int OverHours; // number of overtime hours worked
private double OverPay; // overtime pay
private double GrossPay; // gross pay
// ********** CREATE INPUT STREAMS **********
DecimalFormat df1 = new DecimalFormat ("#####.00"); // to get two decimal places at the end of the numbers
// ********** CONSTRUCTORS ***********
public Employee(int IDnumber)
{ // begin initialized constructor
ID = IDnumber; // set ID to ID number
} // end initialized constructor
// ********** ACCESSORS **********
public int getID()
{ // begin getID
return ID;
} // end getID
public void setWage(double HourlyWage)
{ // begin setWage
Wage = HourlyWage;
} // end setWage
public double getWage()
{ // begin getWage
return Wage;
} // end getWage
public void setHours(int hoursWorked)
{ // begin setHours
Hours = hoursWorked;
} // end setHours
public double getHours()
{ // begin getHours
return Hours;
} // end getHours
// ********** MUTATORS **********
public double getOverPay()
{ // begin getOverPay
if (Hours > MAXHOURS)
{ // begin if hours worked is bigger than MAXHOURS
OverHours = Hours - MAXHOURS;
OverPay = OverHours * Wage * OTRATE;
} // end if hours worked is bigger than MAXHOURS
else
OverPay = 0;
return OverPay;
} // end getOverPay
public double getRegularPay()
{ // begin getRegularPay
return MAXHOURS * Wage;
} // end getRegularPay
public double getGrossPay()
{ // begin getGrossPay
return RegularPay + OverPay;
} // end getGrossPay
public String toString() // overrides the toString method inherited from object
{ // begin toString
String strout = "\nId \t\t Hours \t\t Rate \t\t Regular Pay \t Overtime Pay \t Gross Pay\n";
strout += ID + "\t " + Hours + "\t\t\t $" + (df1.format(Wage)) + "\t\t $" + (df1.format(RegularPay)) + "\t\t\t $" + (df1.format(OverPay)) + "\t\t\t $" + (df1.format(GrossPay));
// df1.format(double) allows me two decimal places
return strout;
} // end toString
} // end class
You are using OvertimePay, GrossPay and RegularPay without using their getters, and these properties haven't been initilizated. You should call the getters.
import java.text.DecimalFormat;
public class Employee
{ // begin class
// *********** CLASS VARIABLES **********
// *********** CLASS CONSTANTS **********
private static int MAXHOURS = 40; // maximum hours before overime
private static double OTRATE = 1.5; // overtime is one and a half
// ********** INSTANCE VARIABLES **********
private int ID; // employee's id
private int Hours; // number of hours worked
private double Wage; // pay per hour
private double RegularPay; // regular pay
private int OverHours; // number of overtime hours worked
private double OverPay; // overtime pay
private double GrossPay; // gross pay
// ********** CREATE INPUT STREAMS **********
DecimalFormat df1 = new DecimalFormat ("#####.00"); // to get two decimal places at the end of the numbers
// ********** CONSTRUCTORS ***********
public Employee(int IDnumber)
{ // begin initialized constructor
ID = IDnumber; // set ID to ID number
} // end initialized constructor
// ********** ACCESSORS **********
public int getID()
{ // begin getID
return ID;
} // end getID
public void setWage(double HourlyWage)
{ // begin setWage
Wage = HourlyWage;
} // end setWage
public double getWage()
{ // begin getWage
return Wage;
} // end getWage
public void setHours(int hoursWorked)
{ // begin setHours
Hours = hoursWorked;
} // end setHours
public double getHours()
{ // begin getHours
return Hours;
} // end getHours
// ********** MUTATORS **********
public double getOverPay()
{ // begin getOverPay
if (Hours > MAXHOURS)
{ // begin if hours worked is bigger than MAXHOURS
OverHours = Hours - MAXHOURS;
OverPay = OverHours * Wage * OTRATE;
} // end if hours worked is bigger than MAXHOURS
else
OverPay = 0;
return OverPay;
} // end getOverPay
public double getRegularPay()
{ // begin getRegularPay
return MAXHOURS * Wage;
} // end getRegularPay
public double getGrossPay()
{ // begin getGrossPay
return getRegularPay() + OverPay;
} // end getGrossPay
public String toString() // overrides the toString method inherited from object
{ // begin toString
String strout = "\nId \t\t Hours \t\t Rate \t\t Regular Pay \t Overtime Pay \t Gross Pay\n";
strout += ID + "\t " + Hours + "\t\t\t $" + (df1.format(Wage)) + "\t\t $" + (df1.format(getRegularPay())) + "\t\t\t $" + (df1.format(getOverPay())) + "\t\t\t $" + (df1.format(getGrossPay()));
// df1.format(double) allows me two decimal places
return strout;
} // end toString
} // end class
You are not printing the state of the employee object but rather the list employeeinfo. You need to iterate over the list and print each employee:
for(Employee e : employeeInfo) {
System.out.println(e.toString());
}
Atleast give me a 1-up for the killer toString method:
import java.util.ArrayList;
import java.util.Scanner;
public class FinalExam
{
public static void main(String[] args)
{
FinalExam finalExam = new FinalExam();
finalExam.run();
}
void run()
{
Employee emp = new Employee();
ArrayList<Employee> list = new ArrayList<>();
Scanner scan = new Scanner(System.in);
System.out.print('\n' + "your employee id: ");
emp.setId(scan.nextInt());
System.out.print('\n' + "hours you worked: ");
emp.setHours(scan.nextInt());
System.out.print('\n' + "your wage:");
emp.setWage(scan.nextDouble());
list.add(emp);
scan.close();
System.out.println(emp.toString());
}
class Employee
{
final private int MAXHOURS = 40;
final private double OTRATE = 1.5;
private int id;
private int hours;
private double wage;
void setId(int id) { this.id = id; }
int getId() { return id; }
void setHours(int hours) { this.hours = hours; }
int getHours() { return hours; }
void setWage(double wage) { this.wage = wage; }
double getWage() { return wage; }
#Override
public String toString()
{
double payRegular, payOvertime,
payGross =
(payRegular = hours > MAXHOURS ? (MAXHOURS * wage) : (hours * wage)) +
(payOvertime = hours > MAXHOURS ? (hours - MAXHOURS) * (wage * OTRATE) : 0);
StringBuilder string = new StringBuilder(500);
string.append("\n");
string.append(
String.format("%10s %10s %10s %15s %15s %15s",
"Id", "Hours", "Rate", "Regular Pay", "Overtime Pay", "Gross Pay"));
string.append("\n");
string.append(
String.format("%10s %10s %10s %15s %15s %15s",
id, hours, wage, payRegular, payOvertime, payGross));
string.trimToSize();
return string.toString();
}
}
}

Account class not working properly

public class AccountDriver {
public static void main(String[] args) {
// ID, Balance, Annual Interest Rate
Account number1 = new Account();
Account number2 = new Account(1122, 20000.00, 0.045);
// Default account
System.out.println("The Account ID is: " + number1.getId());
System.out.println("The Account Balance is: " + number1.getBalance());
// System.out.println("The Account Balance is: "+
// number1.getMontlyInterest());
System.out.println("");
// Ask to withdraw 2500
System.out.println("The Account ID is: " + number2.getId());
number2.withdraw(2500.00);
number2.deposit(3000.00);
System.out.println("Account Balance is " + number2.getBalance());
// System.out.println("The montly interest is : "+
// number2.getMontlyInterest());
System.out.println("");
}
}
public class Account {
private int id = 0;
private double balance = 0;
private double annualInterestRate = 0;
public Account(int id, double balance, double annualInterestRate) {
this.setId(id);
this.setBalance(this.balance);
this.setBalance(annualInterestRate);
}
public Account() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public double getAnnualInterestRate() {
return annualInterestRate;
}
public void setAnnualInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
public double getMontlyInterest(double montlyInterest) {
// Given Formula
// double MontlyInterest= this.balance * get.MontlyInterestRate();
return montlyInterest;
}
public double getMontlyInterestRate(double montlyInterestRate) {
// Given Formula
montlyInterestRate = this.annualInterestRate / 12;
return montlyInterestRate;
}
double withdraw(double amount) {
return balance -= amount;
}
double deposit(double amount) {
return balance += amount;
}
}
I am getting error
The Account ID is: 0
The Account Balance is: 0.0
The Account ID is: 1122
Account Balance is 20500.0
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method getMontlyInterestRate(double) in the type Account is not applicable for the arguments ()
at Account.getMontlyInterest(Account.java:41)
at AccountDriver.main(AccountDriver.java:21)
You did 2 small mistakes in your code.
In your constructor these 2 lines
this.setBalance(this.balance); // this.balance is the instance variable and not the parameter passed
^^^^ - this is not required, just use the balance parameter passed.
this.setBalance(annualInterestRate); // you are re-writing the balance with interest rate
^^^^^^^^^^ - You need to set annual interest rate and not the balance here.
should be
this.setBalance(balance); // sets the balance passed to the instance variable balance
this.setAnnualInterestRate(annualInterestRate); // sets the annual interest rate
Now since the annualInterestRate is set, you can get the monthly interest rate by modifying getMontlyInterestRate method like this.
public double getMontlyInterestRate() {
// Given Formula
return this.annualInterestRate / 12;
}
And you can print your monthly interest rate by uncommenting your System.out.println code.
System.out.println("The montly interest is : "+ number2.getMontlyInterestRate());
And the monthly interest method would look like this:
public double getMontlyInterest() { // no parameter required
// Given Formula
double MontlyInterest = this.balance * getMontlyInterestRate(); // balance multiplied by monthly interest rate
return MontlyInterest; // return the value
}
System.out.println("The montly interest is : "+ number2.getMontlyInterest());

Categories

Resources