Call Superclass method from overridden Subclass method - java

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.

Related

Struggles in using multiple classes

So currently, I'm struggling to make one particular program in eclipse for an assignment, while I am able to make most of the program, I seem to struggle with the no argument part of the program as well as bringing the pieces of the first class into the second for a brief moment. Here is my code for the first class
// Preparation of the input
import java.util.Scanner;
public class primarySetUp {
public static void main(String[] args) {
// Variable Declaration
double userBagNumber;
double userBagWeight;
// Create Scanner
Scanner input = new Scanner(System.in);
java.util.Date date = new java.util.Date();
// Opening Statement
System.out.println("Welcome to the Coffee Sales Simulation!");
// Get User Input
System.out.println("How heavy do you want the bags to be?");
userBagWeight = input.nextDouble();
System.out.println("How many bags do you want?");
userBagNumber = input.nextDouble();
// Get output
// Date
System.out.println("Todays date: ");
System.out.printf("%tB %<te, %<tY", date);
System.out.println(""); // spacer
// Original Inputs
System.out.printf("\nNumber of Bags: %3.0f", userBagNumber);
System.out.printf("\nWeight of Each Bag: %3.2f", userBagWeight);
System.out.print(" lbs");
// Calling of the Class
secondarySetUp mysecondarySetUp = new secondarySetUp(userBagWeight, userBagNumber);
// End Program
System.out.println("\nThank you for shopping with us!");
}
}
and here is my code for the second class, which is full of errors in this case.
public class secondarySetUp {
// Constants
static double pricePerPound = 5.99;
static double taxRate = 0.0725;
int singleBagger, pounderBagger;
public secondarySetUp(double userBagWeight, double userBagNumber) {
// A method named getTaxRate() that returns the tax rate.
System.out.printf("\nPrice per Pound: $%2.2f", getPrice());
System.out.printf("\nSales Tax: $%2.2f", getTaxRate());
System.out.print(" %");
System.out.printf("\nPrice of one bag weighing one pound: %3.2f", getSale());
}
// No argument pricing
public Sale() {
singleBagger = 1;
pounderBagger = 1;
}
// First constructor receiving No argument pricing
public Sale(int w, int n) {
singleBagger = w;
pounderBagger = n;
}
// Sale without tax
public double getSale() {
return userBagWeight * singleBagger * pounderBagger;
}
// Get Sale Tax
public double getSaleTax() {
return (getSale() * taxRate);
}
// Get total pricing
public double getTotalPrice() {
return (getSale() + getSaleTax());
}
public double getPrice() {
return pricePerPound;
}
public double getTaxRate() {
return taxRate * 100;
}
}
If you have any sort of fixes I could apply, please let me know; I am planning on adding the print statements for the rest of the arguments as well, but I'd like to get Sale() fixed up first.
I see a problem in getSale() where you are trying to use userBagWeight, but that variable doesn't exist outside the constructor parameters, which could create a lot of problems since other methods are calling on it. The constructor taking
double userBagWeight, double userBagNumber, yet it's not assigning them to any fields or doing anything with them.
I missed the part where you are treating Sale() as a constructor, but those are no constructors. The constructor is named after your class name.
public secondarySetUp(double userBagWeight, double userBagNumber)
change Sale() to secondarySetUp and you will be fine.
here how your class should be like :
public class secondarySetUp {
// Constants
static double pricePerPound = 5.99;
static double taxRate = 0.0725;
int singleBagger, pounderBagger;
double userBagWeight, userBagNumber;
public secondarySetUp(double userBagWeight, double userBagNumber) {
this.userBagWeight = userBagWeight;
this.userBagNumber = userBagNumber;
singleBagger = 1;
pounderBagger = 1;
// A method named getTaxRate() that returns the tax rate.
System.out.printf("\nPrice per Pound: $%2.2f", getPrice());
System.out.printf("\nSales Tax: $%2.2f", getTaxRate());
System.out.print(" %");
System.out.printf("\nPrice of one bag weighing one pound: %3.2f", getSale());
}
// First constructor receiving No argument pricing
public secondarySetUp(int w, int n) {
singleBagger = w;
pounderBagger = n;
}
// Sale without tax
public double getSale() {
return userBagWeight * singleBagger * pounderBagger;
}
// Get Sale Tax
public double getSaleTax() {
return (getSale() * taxRate);
}
// Get total pricing
public double getTotalPrice() {
return (getSale() + getSaleTax());
}
public double getPrice() {
return pricePerPound;
}
public double getTaxRate() {
return taxRate * 100;
}
}
this is a keyword to tell the program that we want to use the field "instance variable", if we have a method with parameter that have same name as a field name, then to tell them apart we tell the program this.fieldName to know which one we talking about.

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.)

Variable from superclass is not dispalying

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.

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().

Move a method to another method java

import java.util.Scanner;
public class Hw4Part4 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
//Ask for the diners’ satisfaction level using these ratings: 1 = Totally satisfied, 2 = Satisfied,
//3 = Dissatisfied.
System.out.println("Satisfacion leve: ");
int satisfactionNumber= sc.nextInt();
//Ask for the bill subtotal (not including the tip)
System.out.println("What is the bill subtotal: ");
double subtotal= sc.nextInt();
//Report the satisfaction level and bill total.
System.out.println("The satisfaction level is: "+ satisfactionLevel(satisfactionNumber));
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal));
}
public static String satisfactionLevel(int satisfactionNumber){
String satisfactionL = "";
if (satisfactionNumber == 1){
satisfactionL ="Totally-satisfied";
}
if (satisfactionNumber == 2){
satisfactionL = "Satisfied";
}
if (satisfactionNumber == 3){
satisfactionL = "Dissatisfied";
}
return satisfactionL;
}
//This method takes the satisfaction number and returns the percentage of tip to be
//calculated based on the number.
//This method will return a value of 0.20, 0.15, or 0.10
public static double getPercentage(int satisfactionNumber){
double getPercentage = 0;
if (satisfactionNumber ==1){
getPercentage = 0.20;
}
if (satisfactionNumber ==2){
getPercentage = 0.15;
}
if (satisfactionNumber ==3){
getPercentage = 0.10;
}
return getPercentage;
}
public static double getBillTotal(double tipPercentage, double subtotal){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
}
I am having issues on the last method, the whole code is shown above.
It says there is error with the part where I am trying to use the previous method.
I need to get the percentage which was computed on the previous method.
At this part of the code:
public static double getBillTotal(double tipPercentage, double subtotal){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
You call this method:
getPercentage(satisfactionNumber)
However, this variable:
satisfactionNumber
Doesn't exist in this method's scope. You should pass this variable to the method as so:
public static double getBillTotal(double tipPercentage, double subtotal, int satisfactionNumber){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
So when you call the method in the main, you pass it in:
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal, satisfactionNumber));
tipPercentage cannot be resolved to a varible
Pretty much any variable you pass in, you must create. So when you do the above line, make sure you have all variables delcared:
double tipPercentage, subtotal, satisfactionNumber;
//now set these three variables with a value before passing it to the method
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal, satisfactionNumber));
It's hard to tell, but I think you need to remove whitespace:
double totalWithTip = subtotal + (getPercentage(satisfactionNumber) * subtotal);
return totalWithTip;
This code assumes a variable:
int satisfactionNumber;
and a method:
double getPercentage(int satisfactionNumber) {
// some impl
}

Categories

Resources