Getting a value form "get and set" in java - java

I have a school problem that I'm stuck on. The problem is that the gross pay keeps coming up as 0.0.
Here's the question:
Design a Payroll class with the following fields:
• name : a String containing the employee's name
• idNumber: an int representing the employee's ID number
• rate: a double containing the employee's hourly pay rate
• hours: an int representing the number of hours this employee has worked
The class should also have the following methods :
• Constructor : takes the employee's name and ID number as arguments
• Accessors: allow access to all of the fields of the Payroll class
• Mutators: let the user assign values to the fields of the Payroll class
• grossPay: returns the employee's gross pay, which is calculated as the number of
hours worked times the hourly pay rate.
Write another program that demonstrates the class by creating a Payroll object , then
asking the user to enter the data for an employee in the order: name , ID number, rate, hours.
The program should then print out a statement in the following format (for example, if
you had an employee named Chris Jacobsen with ID number 11111, who works for 5 hours at
$10/hr):
Chris Jacobsen, employee number 11111, made $50.00 in gross pay.
Using text forming so that the gross pay is rounded to two decimal places.
Here's what I have so far:
import java.util.Scanner;
public class Payroll
{
private String EmployeeName;
private int IDnumber;
private double HourlyPayRate;
private double TotalHoursWorked;
private double TotalGrossPay;
public Payroll(String Name, int ID, double HourlyRate, double HoursWorked)
{
EmployeeName = Name;
IDnumber = ID;
}
public String getEmployeeName()
{
return EmployeeName;
}
public int getIDnumber()
{
return IDnumber;
}
public void setHourlyPayRate(double HourlyRate)
{
HourlyPayRate = HourlyRate;
}
public double getHourlyPayRate()
{
return HourlyPayRate;
}
public void setTotalHoursWorked(double HoursWorked)
{
TotalHoursWorked = HoursWorked;
}
public double getTotalHoursWorked()
{
return TotalHoursWorked;
}
public void setTotalGrossPay(double GrossPay)
{
TotalGrossPay = GrossPay;
}
public double getTotalGrossPay(double HourlyRate, double HoursWorked)
{
TotalGrossPay = HourlyRate * HoursWorked;
return TotalGrossPay;
}
public static void main(String[] args)
{
String EmployeeName;
int IDnumber;
double TotalHoursWorked;
double HourlyPayRate;
double TotalGrossPay;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter employee's name:");
EmployeeName = keyboard.nextLine();
System.out.print("Enter employee's ID number:" );
IDnumber = keyboard.nextInt();
System.out.print("Enter hourly rate:");
HourlyPayRate = keyboard.nextDouble();
System.out.print("Enter number of hours worked:");
TotalHoursWorked = keyboard.nextDouble();
Payroll pay = new Payroll(EmployeeName, IDnumber, HourlyPayRate, TotalHoursWorked);
System.out.print(EmployeeName + ", " + "employee number " + IDnumber + ", made $" +
pay.TotalGrossPay + " in gross pay.");
}
}
Thanks for any help...

TotalGrossPay is a calculated value, unless you call the methods to calculate it, it will remain as its default value (0)
The fact is, you shouldn't be storing this value anyway, as it's value is actually determine by the calculation of the other fields.
Remove the TotalGrossPay field from your class and write a simple "getter" that calculates the value and returns it...
public double getTotalGrossPay()
{
return HourlyRate * HoursWorked;
}
As a general rule of thumb, you should not be accessing fields directly, but should always be accessing their values (setting/getting) via methods
Also, don't ignore values passed to your constructor...
public Payroll(String Name, int ID, double HourlyRate, double HoursWorked)
{
EmployeeName = Name;
IDnumber = ID;
// What about HourlyRate and HoursWorked??
}
Either make the user supply these vai setters or assign them within your constructor (and yes, you could use the setters to change the values after the fact...)
public Payroll(String Name, int ID, double HourlyRate, double HoursWorked)
{
EmployeeName = Name;
IDnumber = ID;
this.HourlyRate = HourlyRate;
this.HoursWorked = HoursWorked;
}
You might like to have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others

in your constructor you are not doing anything with HourlyRate and HoursWorked
public Payroll(String Name, int ID, double HourlyRate, double HoursWorked)
Why is your getter taking parameters you need to rename it to something like calculateGrossPay(). Remove them and use the instance members HourlyRate and HoursWorked to calculate total gross pay. This is why you are getting a 0.0 as a result
Another point worth noting here is , double variable when uninitialized is set to 0.0 by Java
public double getTotalGrossPay(double HourlyRate, double HoursWorked)

Related

Add a second class to the main class for an annual compensation calculator

I tried searching for this answer and found several answers that were similar to what I am looking for, but I can't seem to apply the suggestions provided on unrelated data to my specific program.
I need to take this working code I have created (a program to calculate an employee's annual compensation) and adjust it in a way that shows two classes (per the instructions of my homework assignment). The output given is exactly what I want, I just need help to reorganize the code so there is more than the main class. Is this something I can get help with here?
Here is my working code:
public class AnnualCompensation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//create salary variable and commission percentage variable
double salary = 60000;
double commissionPercentage = 0.06;
//create command output for the user to get directions to enter value
System.out.println("Enter total amount of sales for the year: ");
double value = input.nextDouble();
double totalCompensation = (value * commissionPercentage) + salary;
System.out.println("Your annual compensation is: " + "$" + totalCompensation);
}
}
Thanks in advance.
create a class Employee with salary and commissionPercentage as the fields.
In constructor take the salary and commision% of employee and initate the fields.
in this class Employee create a method which will take vavlue as input and will calculate the compensation and return it.
So from main create the instance of Employee class and call the calculateMethod.
I would structure it with these classes:
AnnualCompensationCalculator which will do the computation for you as a utility class, and
AnnualCompensation main class which would be focused on requesting for the user input (and would call the calculator).
Suppose you can move the logic inside new class.
AnnualCompensationCalculator.java
public class AnnualCompensationCalculator{
private static double commissionPercentage = 0.06;
public static double calculateCompensation(double sales ,double salary){
return((sales * commissionPercentage) + salary);
}
}
AnnualCompensation .java
public class AnnualCompensation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//create salary variable and commission percentage variable
double salary = 60000;
//create command output for the user to get directions to enter value
System.out.println("Enter total amount of sales for the year: ");
double value = input.nextDouble();
System.out.println("Your annual compensation is: " + "$" + AnnualCompensationCalculator.calculateCompensation(value,salary));
}
}
Following Object Oriented Programming, I suggest you create a new class Employee that holds the salary and compensation percentage of an employee, which also has a method for calculating the compensation.
Like this:
class Employee {
private double salary;
private double commPercent;
public Employee(double salary, double commPercent) {
this.salary = salary;
this.commPercent = commPercent;
}
public double calculateCompensation(double totalSales) {
return (totalSales * commPercent) + salary;
}
/* Setters & Getters */
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public double getCommPercent() {
return commPercent;
}
public void setCommPercent(double commPercent) {
this.commPercent = commPercent;
}
}
Then have your main class use this Employee class to do all the work:
public class AnnualCompensation {
public static void main(String[] args) {
//Initialize an Employee object
Employee emp = new Employee(60000, 0.06);
//Create command output for the user to get directions to enter value
System.out.print("Enter total amount of sales for the year: ");
Scanner input = new Scanner(System.in);
double salesAmt = input.nextDouble();
//Calculate the compensation based on the user input then print it
System.out.println("Your annual compensation is: $"
+ emp.calculateCompensation(salesAmt));
}
}

Java - object can't store data

My dad and I narrowed it down to the object can't store the data. also, I'm new to java. The code is supposed to print in the console the first name, last name, grade, and grade average. I think the problem is in public double getCalcGraeAverage() but correct me if wrong, please.
import java.util.Scanner;
/**
* Write a description of class Student here.
*
* #author XXXX
* #version XXXX
*/
public class Student
{
String firstName;
String lastName;
int gradeLevel;
double gradeAverage;
int totalAssignments;
double totalPoints;
/**
* Create a new student with student's name, grade, and average
*/
public Student(String newFirstName, String newLastName, int newGradeLevel, double newGradeAverage)
{
firstName = newFirstName;
lastName = newLastName;
gradeLevel = newGradeLevel;
gradeAverage = newGradeAverage = 0.0;
}
/**
* Return the student's first name.
*/
public String getFirstName()
{
return firstName;
}
/**
* Return the student's last name.
*/
public String getLastName()
{
return lastName;
}
/**
* Return the grade level of the student.
*/
public int getGradeLevel()
{
return gradeLevel;
}
/**
* Calculates grade average.
*/
public double getCalcGradeAverage()
{
double gradeAverage = totalAssignments / totalPoints;
return gradeAverage;
}
public static void main (String[] args)
{
Student student1 = new Student ("XXXX", "XXXX", 11, 0.0);
System.out.println("The student's first name is: " + student1.getFirstName());
System.out.println("The student's last name is: " + student1.getLastName());
System.out.println("The student's grade level is: " + student1.getGradeLevel());
System.out.println("Please enter the total assignment points the student has earned: ");
Scanner input = new Scanner(System.in);
Double totalAssignments = input.nextDouble();
System.out.println("Please enter the number of assignments given: ");
double totalpoints = input.nextDouble();
System.out.println(student1.getFirstName() + " " + student1.getLastName() + " average grade is" + student1.getCalcGradeAverage());
}
}
In your code you are :
creating a Student student1 object
reading totalAssignments, totalpoints from System.in
calling student1.getCalcGradeAverage()
between steps 2 and 3 you have to set the fields totalAssignments, totalpoints of student to the values you read or they will retain their default values of zero. E.g.
student1.totalAssignments = totalAssignments;
student1.totalpoints = totalpoints;
Also, since totalAssignments is of type int, you probably want to read it as:
int totalAssignments = input.nextInt();
When writing your code, you declare variables for the student class with class scope.
int totalAssignments;
double totalPoints;
those class scope variable are used in the method :getCalcGradeAverage()
totalAssignments of Student and totalPoints of student are used in this method
When you create a new Student those variable are equals to zero because not affected by a value in your constructor.
in the main method when you writes :
Double totalAssignments =
you declare a new variable named "totalAssignments" with a method scope.When the method ends, the variable reference goes away and there is no way to access that variable any longer.
you can consider that the variable decalred is not the same that the student variable: student.totalAssignments is always equals to zero because no value affected to him.
Then assuming that you can do that :
student1.totalAssignments = input.nextInt();
student1.totalPoints = input.nextDouble();

employee class will not calculate correctly

for the assignment, an employee has a ID number, hourly wage and works a certain # of hours. i need to calculate the gross income from those 2 values and then based of that there is withholding from the pay, in my code i believe all that is there but when i test my program i can only calculate the pay that was earned, the withholding and net pay come as a value of 0. i would appreciate any help on the issue, thank you.
// an employee has an ID, get paid an amout hourly and work an amount of hours
// tax is withheld depending on gross pay
public class Employee
{
//withholding calculation
public Employee(String empId, double hrsWrk, double hrPay)
{
employeeId = empId;
hoursWorked = hrsWrk;
hourlyPay = hrPay;
}
// access methods
public String getEmployeeId()
{
return employeeId;
}
public double getHoursWorked()
{
return hoursWorked;
}
public double getHourlyPay()
{
return hourlyPay;
}
public double getWithholding()
{
return withholding;
}
public double getIncome()
{
double income = hourlyPay * hoursWorked;
return income;
}
public double getNetPay()
{
double netPay = income - withholding;
return netPay;
}
// mutator methods
public void setId(String empId)
{
employeeId = empId;
}
public void setHoursWorked(double hrsWrk)
{
hoursWorked = hrsWrk;
}
public void setHourlyPay(double hrPay)
{
hourlyPay = hrPay;
}
//withholding calculator based on income
public void calcWithholding()
{
if(income <= 0)
{
withholding = 0.0;
}
else if(income >0 && income <= 300.0)
withholding = income*10.0/100;
else if(income >= 300.01 && income <= 400.0)
withholding = income*12/100;
else if(income >= 400.01 && income <= 500.0)
withholding = income*15/10;
else
withholding = income*20/100;
System.out.println("withholding is " + withholding);
}
public void displayWithholding()
{
calcWithholding();
System.out.println("Employee " + employeeId + " your income is " + getIncome() + " per week\n you have to pay " + getWithholding());
System.out.println("Employee " + employeeId + " your net income is " + getNetPay());
}
//instance fields
private String employeeId;
private double hoursWorked;
private double hourlyPay;
private double withholding;
private double income;
private double netPay;
}
here is the test program---------------------------------------------
import javax.swing.JOptionPane;
public class EmployeeTest
{
public static void main(String[] args)
{
String employeeId = JOptionPane.showInputDialog("Please enter your Employee ID");
String input = JOptionPane.showInputDialog("Enter your hourly wage");
double hourlyPay = Double.parseDouble(input);
input = JOptionPane.showInputDialog("How many hours have you worked this week?");
double hoursWorked = Double.parseDouble(input);
Employee richard = new Employee(employeeId, hoursWorked, hourlyPay);
richard.displayWithholding();
System.exit(0);
}
}
You're not calling getIncome until after calcWithHolding so the income variable is always zero during the calculation.
The current approach relies on side-effects from calling some of the accessors, this is generally considered to be a bad approach.
I would suggest one of the following
Ensure calculations done in the constructor (or called...)
Separate your concerns so that there is no confusion between data storage, object construction, data accessors and calculations.
Lazy initialization, so that calculated values are only calculated if they have never been accessed.

Writing code - Class - Is this correct/Grade my code [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Requirement:
Write a class, BankAccount, that has two instance variables for the name of the owner (of type String) and the balance (of type double). Add to this class the following methods:
A constructor that initializes the BankAccount instance variables to the values in two parameters, the name of the owner and the initial balance (>=0.0).
deposit: Given an amount (>0.0) to deposit, this method deposits it into the account.
withdraw: Given an amount (>0.0 and <= current balance) to withdraw, this method withdraws it from the account.
getName: This method returns the owner name.
getBalance: This method returns tth current balance. (Don't try to format a number-just take the default.)
Include appropriate checks in your methods to ensure that the amounts deposited and withdrawn satisfy the constraints specified. Use good encapsulation guidelines.
Did I interpret this correctly and execute it correctly and if not what needs fixed and how. Any help is appreciated.
Code:
import java.util.*;
public class BankAccount {
static Scanner in = new Scanner (System.in);
private static String name;
private static double balance;
public BankAccount(String n, double b){
System.out.println("Enter your name: ");
n = in.nextLine();
name = n;
System.out.println("Enter your current balance: ");
b = in.nextDouble();
balance = b;
}
public void deposit(){
System.out.println("Enter the amount you would like to deposit: ");
double deposit = in.nextDouble();
if(deposit > 0.0){
balance = balance + deposit;
}
}
public void withdraw(){
System.out.println("Enter the amount you would like to withdraw: ");
double withdraw = in.nextDouble();
if(withdraw > 0.0 && withdraw <= balance){
balance = balance - withdraw;
}
}
public static String getName(){
return name;
}
public static double getBalance(){
return balance;
}
}
A constructor that initializes the BankAccount instance variables to the values in two parameters, the name of the owner and the initial balance (>=0.0).
Well, you have the constructor, but you override the values passed to it...
public BankAccount(String n, double b){
System.out.println("Enter your name: ");
n = in.nextLine();
name = n;
System.out.println("Enter your current balance: ");
b = in.nextDouble();
balance = b;
}
Should simply be...
public BankAccount(String n, double b){
name = n;
balance = b;
}
deposit: Given an amount (>0.0) to deposit, this method deposits it into the account.
Your deposit method takes no parameters...
public void deposit(double amount){
if (amount > 0.0) {
balance = balance + deposit;
}
}
withdraw: Given an amount (>0.0 and <= current balance) to withdraw, this method withdraws it from the account.
Same as deposit, it takes no parameters...
public void withdraw(double amount){
if (amount > 0.0 && amount <= balance) {
balance = balance - amount;
}
}
getName: This method returns the owner name.
Check...
getBalance: This method returns tth current balance. (Don't try to format a number-just take the default.)
Check...
If it is the normal class for normal uses then this is ok.
But if it is being used in real time financial application then method should be synchornized for thread safe operation and also remove the static variable declaration because static variable belongs to class not to the instance.
Remove the static declarations. Unless you want each instance of BankAccount to refer to the same balance and name. Also your overloaded constructor doesn't need parameters if they aren't used/are set regardless of value.
public class BankAccount {
private Scanner in = new Scanner (System.in);
private String name;
private double balance;
public BankAccount(){
String n = "";
double b = 0.0;
System.out.println("Enter your name: ");
n = in.nextLine();
// check for null string
if(!n.equals("")) {
name = n;
}
System.out.println("Enter your current balance: ");
// ToDo: add a check for input
b = in.nextDouble();
balance = b;
}
...
public String getName(){
return name;
}
public double getBalance(){
return balance;
}
}
You could keep the overloaded constructor and use it in conjunction with the default constructor. Something like...
public BankAccount(){
String n = "";
double b = 0.0;
System.out.println("Enter your name: ");
// ToDo: add a check for input
n = in.nextLine();
System.out.println("Enter your current balance: ");
// ToDo: add a check for input
b = in.nextDouble();
this(n, b);
}
public BankAccount(String n, double b){
// ToDo: add checks for parameter integrity
this.name = n;
this.balance = b;
}

Java: Trouble calling another class

I am just beginning in Java and I am having a peculiar problem that I just cant seem to get to the root of. I have 2 programs and one is taking data from a text file and then calling it into a class to do some calculations and finally putting the output into another text document.
Everything works except this part here:
public class Paycheck
{
//Constants for the private class
private final String EMPLOYEE_NAME; //Employee name
private final String SOC_SEC_NUM; //Employee Social Security Number
private final double WAGE_RATE; //Employee wage
private final double TAX_RATE; //Employee tax withheld
private final double HOURS_WORKED; //Employee's hours of work
//Variables for the private class
private double grossPay; //Employee Gross Pay
private double taxWithheld; //Employee Tax Withheld
private double netPay; //Employee Net Pay
//This is the constructor. It is called whenever an instance of the class is created
public Paycheck (String name, String ssn, double wage, double tax, double hours)
{
EMPLOYEE_NAME = name; //Instance employee name
SOC_SEC_NUM = ssn; //Instance employee SSN
WAGE_RATE = wage; //Instance employee wage rate
TAX_RATE = tax; //Instance employee tax rate
HOURS_WORKED = hours; //Instance employee hours worked
}
//This calculates the variables in the paycheck class
public void calcWages()
{
grossPay = WAGE_RATE * HOURS_WORKED; //Calculates Gross Pay
taxWithheld = grossPay * TAX_RATE; //Calculates Taxes Withheld
netPay = grossPay - taxWithheld; //Calculates net pay
}
//Returns the Paycheck objects Employee Name
public String getEmployeeName()
{
return EMPLOYEE_NAME;
}
//Returns the employee SSN of the Paycheck object
public String getSocSecNum()
{
return SOC_SEC_NUM;
}
//Reeturns a Paycheck object's employee Wage Rate
public double getWageRate()
{
return WAGE_RATE;
}
//Returns a Paycheck object's employee tax rate
public double getTaxRate()
{
return TAX_RATE;
}
//Returns an Paycheck object's employee hours worked
public double getHoursWorked()
{
return HOURS_WORKED;
}
//Returns a Paycheck object's gross pay
public double getGrossPay()
{
return grossPay;
}
//Returns a Paycheck object's Taxes Withheld
public double getTaxWithheld()
{
return taxWithheld;
}
//Returns a paycheck object't net pay
public double getNetPay()
{
return netPay;
}
The calcWages() does the necessary calculations and below this are a series of get statements to call them. However, my output does not return any values for the calcWages() arguments.
I added the getters here and my other program is grabbing them. However the final output on my other program is coming up as 0.
Where am I going wrong here?
This is the part of the main method that is calling them
public static void main(String [] args) throws IOException //Throws clause
{
//Declare constants
final String INPUT_FILE = "Employee.txt"; //Input text file containing Employee information
final String OUTPUT_FILE= "PayrollHistory.txt"; //Output text file that will receive the data
//Declare Variables
String payPeriodDate; //Ending date of the pay period
String employeeName; //Employee Name in text file
String employeeSocSecNum; //Employee SSN in text file
double employeeHours; //Employee hours worked
double employeeTax; //Employee Tax rate
double employeeWage; //Employee Wage rate
double totalGrossPay; //Total employee Gross for pay period
double totalTaxWithheld; //Total Tax Withheld for pay period
double totalNetPay; //Total Net Payroll for pay period
String input; //String input for double conversion in JoptionPane
DecimalFormat money = new DecimalFormat ("#0.00"); // Decimal Format to put money in the right format(USD)
//This ensures that the input file actually exists in the program folder
//And exits the program if it does not, along with the prompt.
File file = new File(INPUT_FILE);
if (!file.exists())
{
JOptionPane.showMessageDialog(null, "The " + INPUT_FILE + " file cannot be found." +
"Program terminated.");
System.exit(0);
}
// Create Scanner object to enable reading data from input file
Scanner inputFile = new Scanner(file);
// Create FileWriter and PrintWriter objects to enable
// writing (appending not overwriting) data to text file
FileWriter fwriter = new FileWriter(OUTPUT_FILE, true);
PrintWriter outputFile = new PrintWriter(fwriter);
//Initialize accumulator values
totalGrossPay = 0.0;
totalTaxWithheld = 0.0;
totalNetPay = 0.0;
//Get the pay period for the employee
payPeriodDate = JOptionPane.showInputDialog("Enter pay period ending date (mm/dd/yyyy):");
outputFile.println("PAY PERIOD ENDING DATE: " + payPeriodDate); //Inputs pay period date into the text file
outputFile.println(); // Blank line
outputFile.println(); // Blank line
while (inputFile.hasNext()) // This will look through the input file and get the necessary variable input
{
// Read employee Name from Input File
employeeName = inputFile.nextLine();
// Read employee SSN from input file
employeeSocSecNum = inputFile.nextLine();
// Read employee Wage Rate from input file
//Parses it into a double type
input = inputFile.nextLine();
employeeWage = Double.parseDouble(input);
//Read employee tax rate from input file
//Parses it into a double type
input = inputFile.nextLine();
employeeTax = Double.parseDouble(input);
//Get number of hours worked
input = JOptionPane.showInputDialog("Employee Name: " + employeeName +
"\nEnter number of hours worked:");
employeeHours = Double.parseDouble(input);
//This call the paycheck class to create a new Paycheck Object
Paycheck employee = new Paycheck (employeeName, employeeSocSecNum, employeeWage, employeeTax, employeeHours);
// Call Paycheck class methods into the output file
outputFile.println("Employee Name: " + employeeName); //Employee Name
outputFile.println("SSN: " + employeeSocSecNum); //Employee SSN
outputFile.println("Hours Worked: " + employeeHours); //Employee Hours Worked
outputFile.println("Wage Rate: " + money.format(employeeWage)); //Employee Wage Rate
outputFile.println("Gross Pay: " + money.format(employee.getGrossPay())); //Employee Gross Pay
outputFile.println("Tax Rate: " + money.format(employeeTax)); //Employee Tax Rate
outputFile.println("Tax Withheld: " + money.format(employee.getTaxWithheld())); //Employee Tax Withheld
outputFile.println("Net Pay: " + employee.getNetPay()); //Employee Net Pay
outputFile.println(); // Blank line
You don't appear to be actually calling calcWages() before calling your getters, so grossPay, taxWithheld, and netPay are still going to be 0, as that's Java's default value for uninitialized numbers.
You need to call employee.calcWages() before referencing those values for them to change.
It is because calcWages() is declared void (public void calcWages()), meaning it is not supposed to return any value but just complete a series of steps (calc payroll particulars in this example). After calling it, just proceed to reference the instance variables it processed.
You have declared your variables as final, meaning they can only be assigned once.

Categories