JAVA Get & Set methods with calculations - java

new to Java and trying to set up get and set methods. Although one I need to do as calculation based off getSalary() multiplied by getMonths() to get a Year to Date total.
I haven't been able to find out if calculations are possible in get or set methods or I may just be such a newbie I have it in the wrong place.
public class Employee_v2
{
//Instance variables
private String first_name;
private String last_name;
private double salary;
private int months;
final double increase= 0.25;
private double year_to_date;
public Employee_v2()
{
//fill in the code to set default values to the instance variables
first_name="";
last_name="";
salary= 0.0;
months= 0;
}
//Constructor initializing instance variables with arguments
public Employee_v2(String f, String l, Double sal, int mo)
{
first_name = f;
last_name = l;
salary = sal;
months = mo;
}
//set arguments
public void setFirst(String f)
{
first_name = f;
}
public void setLast (String l)
{
last_name = l;
}
public void setSalary (double sal)
{
salary = sal;
}
public void setMonths (int mo)
{
months = mo;
}
public void setYtdSalary ()
{
double yearToDateSal;
yearToDateSal = getSalary() * getMonths();
}
//get arguments
public String getFirst()
{
return first_name;
}
public String getLast()
{
return last_name;
}
public double getSalary()
{
return salary;
}
public int getMonths()
{
return months;
}
public double getYtdSalary()
{
return yearToDateSal;
}
//DISPLAY
public void displayEmployee()
{
//display the name and salary of both Employee objects
System.out.println("Employee first name: " + getFirst());
System.out.println("Employee last name: " + getLast());
System.out.printf("Employee salary: $%.2f\n", getSalary());
//complete the code
System.out.println("-------------------------------");
//Determine the year to date salary for both employee
System.out.printf(getFirst() + "'s salary: $%.2f\n", getSalary());
// System.out.println(jas.getSalary());
System.out.printf("Year to date salary: $%.2f\n", getYtdSalary());
//set and display salary with increase
setSalary(getSalary()+ getSalary()*increase);
System.out.printf("New Salary: $%.2f\n", getSalary());
System.out.println();
System.out.println();
}//end method
}//end Class

Calculation are possible in getter and setter. I would do something like this:
public double getYtdSalary(){
double ytd = 0;
ytd = months * salary;
return ytd;
}
Like this you can calculate the year to date on the fly and is always accurate data. For example if you called the setMonths method you would also have to call the setYtdSalary before calling the getYtdSalary.
Also there is no need to call your getters in your class to access your private variables.
I would also suggest using Javadoc comment in your classes as they make it easier to understand what the methods do.

to answer your question: yes it is possible to do calculations
this is also needed in many places, as the main reason to use get and set methods is so you can check or manipulate the values before setting them in your class
I guess your Code will Crash on the printing of the year to date Salary, because the variable yearToDateSal is only valid in the Scope of your set Method.
public void setYtdSalary ()
{
double yearToDateSal;
yearToDateSal = getSalary() * getMonths();
}
you should declare your YearToDateSal variable in the beginning of the class, i.e. rigth after
final double increase= 0.25;
private double year_to_date;
private double yearToDateSal;
and in your setYtdSalary() remove the declaration of yearToDateSal;
this way you should be fine :)

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

Abstract Class Java Why is my program only printing 0.00?

Abstract Class Java Why is my program only printing 0.00?
public class TestEmployee
{
public static void main(String[] args)
{
Employee[] folks = new Employee[4];
folks[0] = new SalariedEmployee("Suzy",123,520000.00);
folks[1] = new WageEmployee("Fred",456,7.50,40);
folks[2] = new SalariedEmployee("Harry",234,45000.00);
folks[3] = new WageEmployee("Rita",345,7.76,38);
for(int i=0; i<folks.length; i++)
{
System.out.println(folks[i].getName()
+ " earns " + folks[i].getMonthlyPay() + " each month");
}
}
}
I added the missing classes needed to make
the program compile and run properly
abstract class Employee
{
private String name;
private int number;
public abstract double getMonthlyPay();
public Employee(String name, int number, double salary)
{
setName(name);
setNumber(number);
salary = getMonthlyPay();
}
public Employee(String name, int number, double salary, int hours)
{
setName(name);
setNumber(number);
salary = getMonthlyPay();
}
public String getName()
{
return this.name;
}
public int getNumber()
{
return this.number;
}
public String setName(String name)
{
this.name = name;
return this.name;
}
public int setNumber(int number)
{
this.number = number;
return this.number;
}
}
Please provide an explanation or insight as to why my program is only printing zeroes. I think this is where my problem lies
class SalariedEmployee extends Employee
{
private double yearSalary;
public SalariedEmployee(String name, int number, double salary)
{
super(name, number, salary);
yearSalary = getMonthlyPay();
}
public double getMonthlyPay()
{
double monthlyPay = yearSalary / 12;
return monthlyPay;
}
public String toString()
{
return(super.getName() + ", " + super.getNumber() + ", " + getMonthlyPay());
}
}
class WageEmployee extends Employee
{
private double wage;
private int hours;
public WageEmployee(String name, int number, double salary, int hours)
{
super(name, number, salary, hours);
}
public double getMonthlyPay()
{
double monthlyPay = wage * hours * 4;
return monthlyPay;
}
public String toString()
{
return(super.getName() + ", " + super.getNumber() + ", " + getMonthlyPay());
}
}
It’s not too difficult to track back to where the 0.00 comes from.
In you for loop in main you use folks[i].getMonthlyPay() to get the number to print. So let’s look into the implementations of getMonthlyPay(). There are two implementations, one in SalariedEmployee and one in WageEmployee.
In case of a SalariedEmployee the getMonthlyPay method uses the value of the field yearSalary. Which value is assigned to yearSalary? Have you editor or IDE find all the occurrences of yearSalary to see where a value is assigned to it. You will see that it happens nowhere. Since yearSalary is a field (more precisely, an instance variable), Java assigns 0.00 to it from the start (local varaibles inside a method are different). Since you never assign any other value, the value is still 0.00 when getMonthlyPay() divides it by 12 and returns the result. So this is where 0.00 comes from. Can you find a way to fix it?
In case of a WageEmployee — you should try the same exercise yourself, find out where the value comes from in WageEmployee.getMonthlyPay(). This time you will need to find out both where the value of wage and where the value of hours come from. Happy searching.

Setters & Getters returning 0 value

For some reason when I input values for RTH and CTH I receive 0.0 values. I had a similar issue on my shift getters, but I managed to fix that. Unfortunately, attempting to reverse engineer the problem hasn't helped. I've provided the code for my class and my driver, although I am almost convinced the issue is somewhere in the class. Nevertheless, can anyone take a quick look at the RTH / CTH setters/ getters and see what I've done wrong in setting or calling them.
public class TeamLeader extends ProductionWorker
{
//private variables
private double RTH;
private double CTH;
private double payRate;
private double monthlyBonus;
//constructor
public TeamLeader(String name, String number, String hd, int shift,
double rate, double monthlyBonus, double RTH, double CTH)
{
super(name, number, hd, shift, rate);
this.monthlyBonus = monthlyBonus;
}
public void setmonthlyBonus(double monthlyBonus)
{
this.monthlyBonus = monthlyBonus;
}
public void setpayRate(double payRate)
{
this.payRate = payRate;
}
public void setRTH(double r)
{
RTH = r;
}
public void setCTH(double c)
{
CTH = c;
}
//Getters
public double getmonthlyBonus()
{
return monthlyBonus;
}
public double getpayRate()
{
return payRate;
}
public double getRTH()
{
return RTH;
}
public double getCTH()
{
return CTH;
}
}
Driver
public class WorkDriver {
public static void main(String[] args) {
String name;
String number;
String hireDate;
int shift;
double payRate;
double monthlyBonus;
double RTH;
double CTH;
name = JOptionPane.showInputDialog("Enter your name");
number = JOptionPane.showInputDialog
("Enter your number (Format: XXX-L)");
hireDate = JOptionPane.showInputDialog("Enter your hire date");
shift = Integer.parseInt(JOptionPane.showInputDialog
("Please enter the work shift for the employee:\n"
+ "\tEnter 1 for the day shift"
+ "\n\tEnter 2 for the night shift"));
payRate = Double.parseDouble(JOptionPane.showInputDialog
("Enter your pay rate"));
monthlyBonus = Double.parseDouble(JOptionPane.showInputDialog
("Enter your monthly bonus"));
RTH = Double.parseDouble(JOptionPane.showInputDialog
("Enter your required traing hours"));
CTH = Double.parseDouble(JOptionPane.showInputDialog
("Enter your training hours attended"));
//Production worker object
TeamLeader driver = new TeamLeader(name, number,
hireDate, shift, payRate, monthlyBonus, RTH, CTH);
JOptionPane.showMessageDialog(null,
"----------- Employe Info ----------------"
+ "\nName: " + driver.getName()
+ "\nEmployee Number: " + driver.getNumber()
+ "\nHire Date: " + driver.getHireDate()
+ "\nPay Rate: " + driver.getPayRate()
+ "\nShift: " + driver.getShift()
+ "\nMonthly Bonus: " + driver.getmonthlyBonus()
+ "\nRequired Training Hours: " + driver.getRTH()
+ "\nTraining Hours Attended: " + driver.getCTH());
System.exit(0);
}
}
You never call the setters of CTH and RTH. You pass their values to your constructor but don't use them.
Add to your constructor setting of CTH and RTH :
public TeamLeader(String name, String number, String hd, int shift,
double rate, double monthlyBonus, double RTH, double CTH)
{
super(name, number, hd, shift, rate);
this.monthlyBonus = monthlyBonus;
this.RTH = RTH;
this.CTH = CTH;
}
You're calling the parent (super) constructor, but it doesn't take RTH or CTH, and you never set RTH and CTH on your TeamLeader object.
public TeamLeader(String name, String number, String hd, int shift,
double rate, double monthlyBonus, double RTH, double CTH)
{
super(name, number, hd, shift, rate);
this.monthlyBonus = monthlyBonus;
this.RTH = RTH;
this.CTH = CTH;
}
You are not setting the passed RTH to the instance's RTH. See code above for the fix

Java set method not working

Hello I'm new to programming and a first time poster here. I'm having trouble getting a Java application to display the correct values assigned via Set methods in a public class. Specifically the CreatePurchase application returns 0 for all 3 user defined variables (invoiceNumber, saleAmount, salesTax) which are Set in the Purchase public class.
Set and display the values here
public class Purchase
{
private int invoiceNumber;
private double saleAmount;
private double salesTax;
public int getInvoiceNumber()
{
return invoiceNumber;
}
public void setInvoiceNumber(int inv)
{
inv = invoiceNumber;
}
public double getSaleAmount()
{
return saleAmount;
}
public void setSaleAmount(double sale)
{
sale = saleAmount;
}
public double getSalesTax()
{
return salesTax;
}
public void setSalesTax(double tax)
{
tax = saleAmount *.05;
tax = salesTax;
}
public static void displayPurchase(Purchase aPurch)
{
System.out.println("Purchase invoice number is " + aPurch.getInvoiceNumber() + "and the sale amount is " + aPurch.getSaleAmount() + "the taxable amount is " +aPurch.getSalesTax());
}
}
This is the CreatePurchase class that prompts the user for the variables and calls the method to display the values for the new object
import java.util.Scanner;
public class CreatePurchase
{
public static void main(String args[])
{
Purchase aPurchase;
aPurchase = getPurchaseInfo();
Purchase.displayPurchase(aPurchase);
}
public static Purchase getPurchaseInfo()
{
Purchase tempPur = new Purchase();
int invoice;
double value;
double value2;
Scanner input = new Scanner(System.in);
System.out.println("Enter the invoice number:");
invoice = input.nextInt();
while(invoice < 1000 || invoice > 8000)
{
System.out.println("You made an invalid selection");
System.out.println("You entered " + invoice);
System.out.println("Please enter a whole number between 1000 and 8000");
invoice = input.nextInt();
}
tempPur.setInvoiceNumber(invoice);
System.out.println("Enter the amount of the sale:");
value = input.nextDouble();
value2 = (value * .05);
while(value < 0)
{
System.out.println("You made an invalid selection");
System.out.println("You entered " + value);
System.out.println("Please enter a non negative number");
value = input.nextDouble();
value2 = (value *.05);
}
tempPur.setSaleAmount(value);
tempPur.setSalesTax(value2);
return tempPur;
}
}
Any direction or advice on how to get the values entered to set and display properly would be greatly appreciated.
The setter needs to assign the new value to the instance field.
public void setSaleAmount(double sale)
{
sale = saleAmount;
}
Yours do the opposite now, switch the assignment around:
public void setSaleAmount(final double sale)
{
this.saleAmount = sale;
}
You can also optionally add final to the parameter (since you don't intend to change it), and make it clear what the instance field is by using this.. Purely optional, but good practice, and in this case either addition would have resulted in a compile-time error to alert you of the mistake.
Your assignments are wrong(for the setters).
It should be salesTax that is set:
public void setSalesTax(double tax)
{
tax = saleAmount *.05;
tax = salesTax; /* wrong assignment(for the purpose) */
}
And so on for your other class variables.
Remember: Setters and Getters are used to modify a class' variables.
All setters need to be modified as below:
public void setSalesTax(double tax)
{
tax = saleAmount *.05;
//tax = salesTax; <-- This line is wrong..
this.salesTax= tax ; // Change this line and it should work...
}
public void setInvoiceNumber(int inv)
{
//inv = invoiceNumber ; --> Invalid setting
this.invoiceNumber = inv; // Correct setting
}
public void setSaleAmount(double sale)
{
//sale = saleAmount; --> Invalid setting
this.saleAmount = sale; // Correct setting
}
Reason:
tax is local variable which is specific to the method setSalesTax.
salesTax is global variable for the object.
While setting value in your object, you need to set it/assign in the global variable salesTax
To avoid confusions, The best way to use a setter would be:
Object Class:
private double amount;
public void setAmount (double amount)
{
this.amount = amount;
}
It is because you do not set the new Value to your object value.
The correct way would be
public void setSalesTax(double tax)
{
tax = saleAmount *.05;
salexTax = tax; //THIS is the mistake
}
Everytime you want to assign a value to an Object, Integer, or whatever, it goes from left to right. So, if you write:
int value=5;
int value2=10;
value2=value;
Value2 is 5 then.
Your setter method is wrong. You must use actual variable on LHS instead of formal argument.
for Ex, setInvoceNumber method should be like below :
public void setInvoiceNumber(int inv)
{
invoiceNumber = inv ;
}
Here inv is formal argument while invoiceNumber is actual variable which is going to store your value in object. You were assigning value of invoiceNumber to inv variable which has no effect in your code. Same goes for all your setter method.

Need some help in Java Inheritance! (In LuxuryCarRental int days is always coming as 0)

Create a class named CarRental that contains fields that hold a renter’s name, zip code, size of the car rented, daily rental fee, length of rental in days, and total rental fee. The class contains a constructor that requires all the rental data accept the daily rate and total fee, which are calculated, based on the size of the car: economy at $29.99 per day, midsize at $38.99 per day, or full size at $43.50 per day. The class also includes a display() method that displays all the rental data.
Create a subclass named LuxuryCarRental. This class sets the rental fee at $79.99 per day and prompts the user to respond to the option of including a chauffeur at $200 more per day. Override the parent class display() method to include chauffeur fee information. Write an application named UseCarRental that prompts the user for the data needed for a rental and creates an object of the correct type. Display the total rental fee.
Save the files as CarRental. java, LuxuryCarRental. java, and UseCarRental. java
public class CarRental
{
String name;
int zip;
String size;
double dailyFee;
int days;
double total;
public CarRental(String size)
{
if(size.charAt(0)=='e')
dailyFee = 29.99;
else if(size.charAt(0)=='m')
dailyFee = 38.99;
else
dailyFee =43.50;
}
public String getname()
{
return name;
}
public int getzip()
{
return zip;
}
public String getsize()
{
return size;
}
public int getdays()
{
return days;
}
public void computetotal(int days)
{
total = dailyFee*days;
}
public void print()
{
System.out.println("The cost of your rental car is $" + total);
}
}
public class LuxuryCarRental extends CarRental
{
public LuxuryCarRental(String size, int days)
{
super(size);
}
public void computetotal1()
{
super.computetotal(days);
dailyFee = 79.99;
total = dailyFee;
System.out.println(days); //trying to see if days still 0
}
}
import javax.swing.*;
import java.util.Scanner;
public class UseCarRental
{
public static void main(String args[]) throws Exception
{
int days;
String name;
int zip;
String size;
Scanner inputDevice = new Scanner(System.in);
System.out.println("Enter days: ");
days= inputDevice.nextInt();
System.out.println("Enter name: ");
name = inputDevice.next();
System.out.println("Enter zip: ");
zip = inputDevice.nextInt();
System.out.println("Enter size: ");
size = inputDevice.next();
CarRental econ = new CarRental(size);
econ.computetotal(days);
econ.print();
CarPhone full = new CarPhone(size, days);
full.computetotal1();
full.print();
}
}
You're not doing anything with days in LuxuryCarRental, your constructor takes it as an argument but does nothing with it. Ideally it should be passed to the CarRental object constructor but in any case, add
this.days = days;
to LuxuryCarRental constructor, or better your CarRental constructor with a new argument.
There is no need to rename your computetotal method either,leave it with the same name; it the child object will override the implementation details from its parent. Look in to polymorphism: http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming
Also, indent your code to make it more readable http://en.wikipedia.org/wiki/Indent_style
You're not initializing days anywhere in both the classes, that's why getdays is returning 0. Please initialize days, before accessing it.
In constructor of CarRental class, make days as an argument, like this:
public CarRental(String size, int days)
{
if(size.charAt(0)=='e')
dailyFee = 29.99;
else if(size.charAt(0)=='m')
dailyFee = 38.99;
else
dailyFee =43.50;
this.days = days;
}
In LuxuryCarRental's constructor, do this:
public LuxuryCarRental(String size, int days)
{
super(size, days);
}

Categories

Resources