Variable from superclass is not dispalying - java

I'm having a problem which I cannot fathom why. I have program I'm making where it takes a few inputs and calculates pay, tax, and final pay.
Everything is working except the final pay.
this calculates the final pay
import java.util.*;
public class Payroll extends Pay
{
public double calc_payroll()
{
super.calc_payroll();
super.tax();
netPay = grossPay - (grossPay * (tax/100));
return netPay;
}
}
this calculates pay and tax
import java.util.*;
public class Pay
{
private float hoursWrkd;
private float rate;
private int hoursStr;
float grossPay;
int tax;
float netPay;
public double calc_payroll()
{
grossPay = getHoursWrkd()*getRate();
return grossPay;
}
public double tax()
{
if (grossPay <= 399.99)
{
tax = 7;
}
else if (grossPay >= 400.00 && grossPay <= 899.99)
{
tax = 11;
}
else if (grossPay <= 900.00)
{
tax = 15;
}
return tax;
}
//Get & Set for hours worked
public float getHoursWrkd()
{
return hoursWrkd;
}
public void setHoursWrkd(float hoursWrkd)
{
this.hoursWrkd = hoursWrkd;
}
//Get & Set for Rate
public float getRate()
{
return rate;
}
public void setRate(float rate) {
this.rate = rate;
}
//Get & Set for hours straight
public int getHoursStr()
{
return hoursStr;
}
public void setHoursStr(int hoursStr)
{
this.hoursStr = hoursStr;
}
}
and this displays all
public class CalPayroll extends Pay
{
public void displayInfo()
{
super.calc_payroll();
super.tax();
Payroll colio = new Payroll();
colio.calc_payroll();
NumberFormat dollars = NumberFormat.getCurrencyInstance();
System.out.println("Gross Pay is : " + dollars.format(grossPay));
System.out.println("Tax is : " + tax + "%");
System.out.println("Net Pay is : " + dollars.format(netPay));
}
i have more files but those are the ones that just take the input, and call the other files.
The math is correct, however when i try to call the netPay variable and format it, it dosn't display any ammount. With grosspay it works. However my teacher said were supposed to pass grosspay into tax so it can use it, im not sure if that would fix it.
PLease help.

You try to display the netPay from CalPayroll, but this class never computes this value. When you do
Payroll colio = new Payroll();
colio.calc_payroll();
You’re probably expecting the netPay to be calculated in CalPayrool, but you’re actually calculating a separate value in a separate object, which has no effect on the current object.

Related

I am not able to get it do the deductions right on payroll program in java. error I am getting is one of my variables has not been initialized

I am getting an error that says: C:\Users\Jasmi\payroll\src\Payroll.java:68:38
java: variable grossPay might not have been initialized, but I am not sure how to fix it.
public class Payroll {
public String calculateGrossPay;
public String calculateNetPay;
private String name;
private int idNumber;
private double hourlyPayRate;
private double hoursworked;
Payroll(String nameGiven, int idNumbergiven) {
name = nameGiven;
idNumber = idNumbergiven;
hourlyPayRate = 7.15;
hoursworked = 0;
}
public String getName() {
return name;
}
public int getIDNumber() {
return idNumber;
}
public double getHourlyPayrate() {
return hourlyPayRate;
}
public double getHoursWorked() {
return hoursworked;
}
public void setName(String nameGiven) {
name = nameGiven;
}
public void setIDNumber(int idNumbergiven) {
idNumber = idNumbergiven;
}
public void setHourlyPayRate(double hourlypayrategiven) {
hourlyPayRate = hourlypayrategiven;
}
public void setHoursWorked(double hoursworkedgiven) {
hoursworked = hoursworkedgiven;
}
//gross pay plus overtime
public double calculateGrossPay() {
double overtime;
overtime = 0;
double grossPay;
if (hoursworked < 40) grossPay = hourlyPayRate * hoursworked;
else {
overtime = hoursworked - 40;
grossPay = (overtime * 1.5 * hourlyPayRate) + (40 * hourlyPayRate);
}
return grossPay;
}
//deductions
public double calculateNetPay() {
double netPay;
double grossPay;
double deduction = (.2579) * grossPay;
return netPay;
}
}
Here is the second document:
import javax.swing.JOptionPane;
public class PayrollClassTest {
public static void main(String[] args) {
String userInputString;
String userName;
int userId;
double userhourlyPayRate;
double userHoursworked;
userName = JOptionPane.showInputDialog("enter the name of this employee: ");
userInputString = JOptionPane.showInputDialog("Please enter employee ID: ");
userId = Integer.parseInt(userInputString);
userInputString = JOptionPane.showInputDialog("Please enter Hourly Pay Rate: ");
userhourlyPayRate = Double.parseDouble(userInputString);
userInputString = JOptionPane.showInputDialog("Enter the hours worked: ");
userHoursworked = Double.parseDouble(userInputString);
Payroll payroll1 = new Payroll(userName, userId);
payroll1.setHourlyPayRate(userhourlyPayRate);
payroll1.setHoursWorked(userHoursworked);
System.out.println(payroll1.getName() + " has a gross pay of " + payroll1.calculateGrossPay());
System.out.println(payroll1.getName() + " has a net pay of " + payroll1.calculateNetPay());
System.exit(0);
}
private static void calculateGrossPay() {
}
private static void calculateNetPay() {
}
}
I have tried to change deductions to be shown as this:
//deductions
public double calculateNetPay() {
double netPay = 0;
double grossPay = 0;
double deduction = (.2579) * grossPay;
return netPay;
}
}
It does work, but the results do not show the deductions:
Here is an example of the results:
Betty has a gross pay of 13000.0
Betty has a net pay of 0.0
Process finished with exit code 0
This is when I put name as Betty, gross pay as 100, and hours worked as 100. It shows the overtime correctly, but not the deductions.
Any help is greatly appreciated. thanks!
If my understanding of the code is correct then the following is where you are wrong for this piece of code.
public double calculateNetPay() {
double netPay = 0;
double grossPay = 0;
double deduction = (.2579) * grossPay;
return netPay;
}
First: netPay has no value assigned
This method will always return 0.
Reason : The netPay variable is declared and initialized to 0.
What you probably want to do before your return statement is perhaps;
netPay = grossPay - deduction;
I could be wrong in that logic, but I am definitely right when I say that you need to put some value to netPay before you return it.
Second: grossPay has no value assigned
In this method, you multiple .2579 with grossPay, but grossPay is 0 that you have now initialized.
You are assuming that the variable grossPay is shared for the two methods calculateGrossPay and calculateNetPay.
That is not true.
These are both two separate local variables that are declared separately in two different methods and have two different scopes.
You can read more about scope of java variables here:
variable docs from oracle
"in scope" meaning in java : StackOverflow question
My recommendation is to make grossPay a class variable instead of a method variable so that it could be shared between the two methods of the same class instance. (Assuming you are calling calculateGrossPay before calculateNetPay every time, so that grossPay can have the right value assigned to it.)

How do I implement a method for calculating overtime pay in an HourlyWorker class

I have an assignment which asks for everything I have in the code below. That all works fine - I just need to calculate any monthly hours over 160 hours to be paid at 1.5 times the normal hourly rate. My math seems sound and calculates fine:
((hours - 160) * overtime) + (160 * hourlyRate)
But I dont know if I'm putting this if statement in the right method or if it even should be an if statement. My increase/decreasePay methods are working prior to this and they need to stay. I removed some things so it's easier to read.
HourlyWorker Class:
public class HourlyWorker extends Employee
{
private int hours;
private double hourlyRate;
private double monthlyPay;
private double overtime = (1.5 * hourlyRate);
public HourlyWorker(String last, String first, String ID, double rate)
{
super(last, first, ID);
hourlyRate = rate;
}
public void setHours(int hours)
{
this.hours = hours;
}
public int getHours()
{
return hours;
}
public void setHourlyRate(double rate)
{
this.hourlyRate = rate;
}
public double getHourlyRate()
{
return hourlyRate;
}
public double getMonthlyPay()
{
if (hours > 160)
{
monthlyPay = ((hours - 160) * overtime) + (160 * hourlyRate);
}
else
{
monthlyPay = hourlyRate * hours;
}
return monthlyPay;
}
public void increasePay(double percentage)
{
hourlyRate *= 1 + percentage / 100;
}
public void decreasePay(double percentage)
{
hourlyRate *= 1 - percentage / 100;
}
}
What I'm testing with:
public class TestEmployee2
{
public static void main(String[] args)
{
Employee [] staff = new Employee[3];
HourlyWorker hw1 = new HourlyWorker("Bee", "Busy", "BB1265", 10);
hw1.setHours(200);
staff[0] = hw1;
System.out.println(staff[0].getMonthlyPay());
staff[0].increasePay(10);
System.out.println(staff[0].getMonthlyPay());
}
}
Output is:
1600 (initial monthly rate, with 40 overtime hours and 160 regular hours)
1760 (10% increase to the monthlyPay)
Should be:
2006
2206.6
You code has the following issues:
Field initializers run before the body of the constructor, so overtime = (1.5 * hourlyRate) uses the default value of 0 for the hourlyRate field, calculating an overtime value of 0, and is never recalculated, since initializers only run once, during initialization.
setHourlyRate() updates the hourlyRate field, but doesn't re-calculate the value for the overtime field. Same for increasePay() and decreasePay().
There is no point to the monthlyPay field, since you never really use it, given that you only use it as-if it was a local variable in the getMonthlyPay() method.
Get rid of fields monthlyPay and overtime, and make them both local variables in the getMonthlyPay() method.
FYI: Using double for currency amounts is discouraged. The recommended type for currency in Java is BigDecimal.

Account and Test Account Interest class

I would like someones expert opinion on both of my account class and the test account interest class. The issue I am facing is that the code from the test account interest class just multiplies on from the previous 12 month compute interest when it is supposed to be used only once.
The issue is in the
public double computeInterest(int n)
{
balance=balance*(Math.pow((1+rate),n/12));
return balance;
}
It is in this method of where the problem is that I should not use the balance but to use a variable that will store the answer but I did not understand the person that very clearly and he was very vague by only stating a variable should be used.
public class Account
{
private double balance; //STATE
private double interestRate; //STATE
private double rate;//STATE
public Account()
{
balance = 0;
interestRate = 0;
}
public Account(double amount, double interestRate)
{
balance = amount;
rate = interestRate;
}
public void deposit(double amount)
{
balance=balance+amount;
}
public void withdraw(double amount)
{
balance = balance - amount;
}
public void setInterest(double rate)
{
balance = balance + balance * rate;
//this.setInterst = setInterest;
//setInterest = InterestRate / 12;
}
public double computeInterest(int n)
{
balance=balance*(Math.pow((1+rate),n/12));
return balance;
}
public double getsetInterest()
{
return rate;
}
public double getBalance()
{
return balance;
}
public void close()
{
balance =0;
}
}
This is my test account interest class:
public class TestAccountInterest
{
public static void main (String[] args)
{
Account acc1 = new Account(100, 0.1);//0.10);
Account acc2 = new Account(133, 0.2); //0.20);
/*************************************
ACC1 ACCOUNT BELOW
*************************************/
//acc1.deposit(100);
//acc1.withdraw(100);
System.out.println(acc1.computeInterest(12));
// //acc1.computeInterest(12);
// System.out.println(acc1.computeInterest(24));
/**************************************
ACC2 ACCOUNT BELOW
**************************************/
acc2.withdraw(100);
acc2.deposit(100);
//acc2.computeInterest(24);
System.out.println(acc2.computeInterest(24));
}
}
This is the final output:
110.00000000000001
191.51999999999998
As you can see for the second one the figure is multiplied by the 12 month compute interest with the 24 month compute interest this stems from the method in the account class:
public double computeInterest(int n)
{
balance=balance*(Math.pow((1+rate),n/12));
return balance;
}
If I take out the balance it still causes and error so I confused on this particular part.
Code,
public double computeInterest(int n) {
balance = balance * (Math.pow((1 + rate), n / 12));
return balance;
}
should be changed to
public double computeInterest(int n) {
return balance * Math.pow(1 + rate, n / 12);
}
You shouldn't change balance field while computing interest. You might like to have a separate method to update balance where you do , balance = balance + computed_interest or something like that.
Also, I have remove unnecessary parenthesis. That was not an error but simply making your code less readable.

Call Superclass method from overridden Subclass method

I'm sure this has a simple solution, but I'm new to Java and can't work it out.
I have a subclass Payroll that extends a superclass Pay, it contains an overridden method called 'calc_payroll'. From this method, I want to call the superclass method of the same name, and assign the output to a variable in the overriding method. My code is below
public class Payroll extends Pay
{
public double calc_Payroll()
{
double grossPay = super.calc_Payroll();
double taxAmt = tax(grossPay);
double netPay = grossPay - taxAmt;
System.out.println(grossPay);
return netPay;
}
}
Below is the code from the calc_payroll method in the superclass
public double calc_Payroll()
{
double otRate = rate * 1.77;
double otHours = ttlHours - stHours;
if(stHours == 0)
{
grossPay = otHours * rate;
}
else
{
grossPay = ((stHours * rate) + (otHours * otRate));
}
System.out.println(stHours + "//" + otHours + "//" + rate);//for testing
return grossPay;
}
the superclass method functions without issue to calculate and return the gross pay when called from a different subclass, but when calling it from a method with the same name, the print line in the code above (that I have labelled for testing) displays zero's for all variables
Code for full 'Pay' class is below as requested
public class Pay
{
private double ttlHours;
private int stHours;
private double rate;
double grossPay = 0.0;
final double TAXL = 0.07;
final double TAXM = 0.1;
final double TAXH = 0.16;
public void SetHours(double a)
{
ttlHours = a;
}
public void SetHoursStr(int a)
{
stHours = a;
}
public void SetRate(double a)
{
rate = a;
}
public double GetHours()
{
return ttlHours;
}
public int GetStHours()
{
return stHours;
}
public double GetRate()
{
return rate;
}
public double taxRate()
{
double taxRate = 0.0;
if(grossPay <= 399.99)
{
taxRate = TAXL;
}
else if(grossPay <= 899.99)
{
taxRate = TAXM;
}
else
{
taxRate = TAXH;
}
return taxRate;
}
public double tax(double grossPay)
{
double ttlTax = 0.0;
if(grossPay < 400.00)
{
ttlTax += (grossPay * TAXL);
}
else if(grossPay < 900.00)
{
ttlTax += (grossPay * TAXM);
}
else
{
ttlTax += (grossPay * TAXH);
}
return ttlTax;
}
public double calc_Payroll()
{
double otRate = rate * 1.77;
double otHours = ttlHours - stHours;
if(stHours == 0)
{
grossPay = otHours * rate;
}
else
{
grossPay = ((stHours * rate) + (otHours * otRate));
}
System.out.println(stHours + "//" + otHours + "//" + rate);//for testing
return grossPay;
}
}
The subclass Payroll contains no other code
Below is the code that accepts user input to assign values to the initialized variables
public class CalPayroll extends Pay
{
Payroll nPay = new Payroll();
Accept Read = new Accept();
public void AcceptPay()
{
char select = '0';
while(select != 'e' && select != 'E')
{
System.out.println("Payroll Computation \n");
System.out.print("Enter number of hours worked (00.0) <0 for Quick exit>: ");
SetHours(Read.AcceptInputDouble());
System.out.print("Enter first number of hours straight (integer or 0 to disable): ");
SetHoursStr(Read.AcceptInputInt());
System.out.print("Enter hourly rate of worker (00.00): ");
SetRate(Read.AcceptInputDouble());
Screen.ScrollScreen('=', 66, 1);
Screen.ScrollScreen(1);
displayInfo();
System.out.println("e to exit, any other letter + <Enter> to continue");
select = Read.AcceptInputChar();
}
}
public void displayInfo()
{
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
System.out.println("Gross pay is :" + currency.format(calc_Payroll()));
System.out.println("Tax is :" + percent.format(taxRate()));
System.out.println("Net pay is :" + currency.format(nPay.calc_Payroll()));
Screen.ScrollScreen(1);
}
}
I'm confused!
Its clear from you code that ttlHours, stHours and rate are not initialised with some reasonable value. So when you just call super.calc_Payroll(), values like 0 or 0.0 are used as i explained in my comment. Its good to first set values of these variables before calling super.calc_Payroll().
SetHours(23.4); //some value
SetHoursStr(5); //some value
SetRate(2.3); //some value
Also you don't have constructor for Pay class, try making it and initialising all uninitialised variable in constructor or use setter/getter methods to set and get values.
Since your both classes extends Pay class, it creates the problem which you are facing. When you call SetHours(Read.AcceptInputDouble()), it set the variable inherited by CalPayroll from Pay, not the variables inherited by Payroll class. What you have to do is to set variables for Payroll instance as well as for current class as both extends Pay. Do the following replace your while loop as,
while(select != 'e' && select != 'E')
{
System.out.println("Payroll Computation \n");
System.out.print("Enter number of hours worked (00.0) <0 for Quick exit>: ");
SetHours(Read.AcceptInputDouble());
nPay.SetHours(GetHours());
System.out.print("Enter first number of hours straight (integer or 0 to disable): ");
SetHoursStr(Read.AcceptInputInt());
nPay.SetHoursStr(GetStHours());
System.out.print("Enter hourly rate of worker (00.00): ");
SetRate(Read.AcceptInputDouble());
nPay.SetRate(GetRate());
Screen.ScrollScreen('=', 66, 1);
Screen.ScrollScreen(1);
displayInfo();
System.out.println("e to exit, any other letter + <Enter> to continue");
select = Read.AcceptInputChar();
}
Please post the complete code.
It seems that for some reason your variables of super class method not getting assigned values properly. And they are initialized with their default values which is making everything 0. I'll be able to help better if you paste the complete class.

How to pass a variable between methods without parameters and arguments

I'm having a bit of an issue with a school project of mine. We're supposed to write a Loan class that will do things associated with, well, loans, such as return the monthly payment and the total payment on the loan. My problem is that I have specific instructions for this code that I absolutely cannot go outside of.
Here's the code:
import java.util.Scanner;
import java.text.DecimalFormat;
import java.lang.Math;
public class Loan
{
public double annualInterestRate = 0;
public int numberOfYears = 0;
public double loanAmount = 0;
public Loan()
{
annualInterestRate = 0.025;
numberOfYears = 1;
loanAmount = 1000;
}
public Loan(double interestRate, int numYears, double amount)
{
setRate(interestRate);
setYears(numYears);
setLoanAmount(amount);
}
public void setRate(double interest)
{
DecimalFormat percent = new DecimalFormat( "0.0%" );
if(interest > 25 || interest < 0)
{
System.out.println("WARNING: Invalid annual interest rate: " + percent.format(interest) + ".");
System.out.println("Current value not changed: " + percent.format(annualInterestRate * 100) + ".");
}
else
{
annualInterestRate = interest;
}
}
public void setYears(int years)
{
if(years > 30 || years <= 0)
{
System.out.println("WARNING: Invalid number of years: " + years + ".");
System.out.println("Current value not changed: " + numberOfYears + ".");
}
else
{
numberOfYears = years;
}
}
public void setLoanAmount(double amnt)
{
DecimalFormat loan = new DecimalFormat( "$#,##0.00" );
if(amnt <= 0)
{
System.out.println("WARNING: Invalid loan amount: " + loan.format(amnt) + ".");
System.out.println("Current value not changed: " + loan.format(amnt) + ".");
}
else
{
loanAmount = amnt;
}
}
public double getAnnualInterestRate()
{
return annualInterestRate;
}
public int getNumberOfYears()
{
return numberOfYears;
}
public double getLoanAmount()
{
return loanAmount;
}
public double getMonthlyPayment()
{
double monthly = annualInterestRate/12;
double monthlyPayment = (loanAmount * monthly)/1 - (1/(1 + monthly));
monthlyPayment = Math.pow(monthlyPayment, 12);
return monthlyPayment;
}
public double getTotalPayment()
{
double totalPayment = getmonthlyPayment() * 12;
return totalPayment;
}
public String toString()
{
DecimalFormat percent = new DecimalFormat( "0.0%" );
DecimalFormat loan = new DecimalFormat( "$#,##0.00" );
String interestRate = percent.format(annualInterestRate);
String numOfYears = Integer.toString(numberOfYears);
String loanAmnt = loan.format(loanAmount);
String total = "Annual Interest Rate:\t" + interestRate + "\nNumber of Years:\t\t" + numOfYears + "\nLoan Amount:\t\t\t" + loanAmnt;
return total;
}
}
My problem is with the getTotalPayment method. It can't access the monthlyPayment variable without me either declaring monthlyPayment as a field, like annualInterestRate, or passing it to the getTotalPayment method. The issue is, getTotalPayment is not allowed to have parameters, and we aren't allowed to have any more fields than the three she instructed us to have, which are the three you'll see declared in the beginning of the code.
So, my question: is there a way to make the variable monthlyPayment accessible to getTotalPayment, without making monthlyPayment a field or giving getTotalPayment a parameter?
You have a spelling error in your getTotalPayment() method.
What your trying to do is call the method getmonthlyPayment() when you should be calling getMonthlyPayment().
Incase you missed the suttle difference in my answer you have a lowercase 'm' when you want an uppercase 'M'.
Im not entirety sure if this is your problem, but its the only syntax error my IDE is telling me.
In your revised code you need upper case M in call to getMonthlyPayment().

Categories

Resources