employee class will not calculate correctly - java

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.

Related

my display() is not running or showing my println

The program I am working on currently runs successfully but it doesn't execute part of my program and it shows no errors.
The prompt was:
"Create an application that declares a Purchase object and prompts the user for purchase details. When you prompt for an invoice number, do not let the user proceed until a number between 1000 and 8000 has been entered. When you prompt for a sale amount, do not proceed until the user has entered a non-negative number, sale amount, and sales tax. Save the file as CreatePurchase.java."
import java.util.Scanner;
public final class CreatePurchase {
static int invoiceNum; // I made these variables static because
static double amount; // it fixed an error I was having with using
// non-static variables in a static field?
double tax = .05;
double totalamount;
public static void main(String[] args) {
Purchase completedPurchase = new Purchase();
Scanner input = new Scanner(System.in);
System.out
.println("Please enter the invoice number! (Must be between 1000 and 8000!)");
invoiceNum = input.nextInt();
System.out
.println("Please enter the amount of the sale! (Must be greater than 0!)");
amount = input.nextDouble();
while (invoiceNum < 1000 || invoiceNum > 8000) {
System.out
.println("The invoice number you entered is invalid, try again!");
}
while (amount < 0) {
System.out.println("The sale amount is invalid, try again!");
}
}
public int getInvoiceNum(int invoiceNum) {
return invoiceNum;
}
public double getAmount(double amount) {
return amount;
}
public double getTotalAmount(double totalAmount) {
return totalAmount;
}
public void setTotalAmount(double tax, double amount) {
double totalAmount = (amount * tax);
}
public void display(int invoiceNum, double amount, double totalAmount) {
System.out.println("Your invoice number is:" + invoiceNum + ".");
System.out.println("Your sale amount is: " + amount + ".");
System.out.println("Your sale amount after tax is: " + totalAmount
+ ".");
}
}
I have spent hours trying to figure out what I need to fix in order to get my display method to work. The program runs successfully, and there are no errors, so I am not sure what to even try to fix.
(Sorry if my code or question doesn't make sense.)
I would massively refactor your code if given the chance. First, the CreatePurchase class should be a simply POJO (plain old Java object), containing state for the invoice number, purchase amount, and sales tax, along with getter and setter methods for accessing and changing that state. Next, the main() method within this class will instantiate a CreatePurchase object for storing the user input. A big change I made was in how the code handles user inputs. My code below uses two while loops to poll the user for a correct invoice number (between 1000 and 8000) and amount (non negative), and only then proceeds with the remainder of the method. Finally, the CreatePurchase object created is used to output the result to the console.
public final class CreatePurchase {
private int invoiceNum;
private double amount;
private double totalamount;
// I am hard-coding the sales tax as 5%, as you did in your question,
// though this code can easily be modified if you also want to input the tax
private final double tax = .05;
public int getInvoiceNum() {
return invoiceNum;
}
public void setInvoiceNum(int invoiceNum) {
this.invoiceNum = invoiceNum;
}
public double getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public double getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(double totalAmount) {
this.totalAmount = totalAmount;
}
public static void main(String[] args) {
CreatePurchase cp = new CreatePurchase();
Scanner input = new Scanner(System.in);
// these next two do-while loops will continue polling the user
// until he enters a valid input
do {
System.out.println("Please enter the invoice number! (Must be between 1000 and 8000!)");
invoiceNum = input.nextInt();
} while (invoiceNum < 1000 || invoiceNum > 8000);
cp.setInvoiceNum(invoiceNum);
do {
System.out.println("Please enter the amount of the sale! (Must be greater than 0!)");
amount = input.nextDouble();
} while (amount < 0);
totalamount = amount*(1 + tax);
cp.setAmount(amount);
cp.setTotalAmount(totalAmount);
// now use the CreatePurchase object to print out
// details of the transaction
System.out.println("Your invoice number is:" + cp.getInvoiceNum() + ".");
System.out.println("Your sale amount is: " + cp.getAmount() + ".");
System.out.println("Your sale amount after tax is: " + cp.getTotalAmount() + ".");
}
}
You declared method public void display(int invoiceNum, double amount, double totalAmount) but you never actually used it.
try the below code, this should help!
import java.util.Scanner;
public final class CreatePurchase {
static int invoiceNum; // I made these variables static because
static double amount; // it fixed an error I was having with using
// non-static variables in a static field?
static double tax = .05;
static double totalAmount;
public void updatePurchase(final Purchase purchase) {
Scanner input = new Scanner(System.in);
System.out
.println("Please enter the invoice number! (Must be between 1000 and 8000!)");
invoiceNum = input.nextInt();
if (invoiceNum < 1000 || invoiceNum > 8000) {
System.out
.println("The invoice number you entered is invalid, try again!");
updatePurchase(purchase);
}
System.out
.println("Please enter the amount of the sale! (Must be greater than 0!)");
amount = input.nextDouble();
if (amount < 0) {
System.out.println("The sale amount is invalid, try again!");
updatePurchase(purchase);
}
setTotalAmount(tax, amount);
display(invoiceNum, amount, getTotalAmount());
}
public static void main(String[] args) {
Purchase completedPurchase = new Purchase();
new CreatePurchase().updatePurchase(completedPurchase);
}
public int getInvoiceNum(int invoiceNum) {
return invoiceNum;
}
public double getAmount(double amount) {
return amount;
}
public double getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(double tax, double amount) {
totalAmount = (amount * tax);
}
public void display(int invoiceNum, double amount, double totalAmount) {
System.out.println("Your invoice number is:" + invoiceNum + ".");
System.out.println("Your sale amount is: " + amount + ".");
System.out.println("Your sale amount after tax is: " + totalAmount
+ ".");
}
}

Java, Overloading method

I have an assignment for class and it's to go over inheritance and overloading and overriding methods. I think I did everything asked for in the instructions. However, I am a little confused about overloading and if I did it correctly. Actually not really sure how it works so I don't know if I did it all. So you do not have to read through the directions, my main question refers to, the directions that ask "Create two overloaded deposit methods in Account class such that one of them takes an integer value as the input parameter and the second one takes a double value as the input parameter." and I am not sure I did it correctly.
THANKS FOR ANY HELP!!!
Scott
Instructions available upon request.
Here is what I have....
ACCOUNT CLASS (super class)
//Account class
public class Account {
//create data fields
Scanner scan = new Scanner(System.in);
protected int id = 0;
protected double balance = 0;
protected double annualInterestRate = 0;
protected Date dateCreated;
public Account() {
dateCreated = new Date();
}
//constructor for account w/ with id and balance args.
public Account(int newID, double newBalance, double interestRate) {
dateCreated = new Date();
id = newID;
balance = newBalance;
annualInterestRate = interestRate;
}//end account method
//setter for account ID
public int setID(int newID) {
return id = newID;
}//end setID
//getter for account ID
public int getID() {
return id;
}//end getID
//setter for account balance
public void setBalance(double newBalance) {
balance = newBalance;
}//end setBalance
//getter for account balance
public double getbalance() {
return balance;
}//end method getBalance
//setter for accounts annual interest rate
public void setAnnualInterestrate(double newAnnualInterestRate) {
annualInterestRate = newAnnualInterestRate;
}//end setAnnualInterestRate
//getter for accounts annual interest rate
public double getAnnualInterestRate() {
return annualInterestRate;
}//end getAnnualInterestRate
//getter for date account was created
public Date getDateCreated() {
return dateCreated;
}//end getDateCreated
//calls the annual interest rate and divides by 12 to get the monthly rate
public double getMonthlyInterestRate() {
return (annualInterestRate) / 12;
}//end getMonthlyInterestRate
//method to make a withdrawal from account
public double withdraw(double withdrawAmount) {
balance -= withdrawAmount;
return withdrawAmount;
}
//two overload method to make a deposit from account
public void deposit(double depositAmount) {
balance += depositAmount;
}
public void deposit(int depositAmount) {
balance += depositAmount;
}
}
SAVINGS ACCOUNT CLASS
public class SavingAccount extends Account {
public SavingAccount(int newID, double newBalance, double interestRate) {
super(newID, newBalance, interestRate);
}
public double withdraw(double withdrawAmount){
if(balance >= withdrawAmount){
return super.withdraw(withdrawAmount);
}
else{
System.out.println("You cannot be overdraw your Savings Account! \nThe max you will be allowed to withdraw is: " + balance + "\n");
setBalance(0);
return balance;
}
}
#Override
public String toString() {
return "Account ID: " + id + "\nBalance: " + balance + "\nAnnual Interest rate: "
+ annualInterestRate + "\nDate of the Account Creation:" + dateCreated;
}
}
CHECKING ACCOUNT CLASS
public class CheckingAccount extends Account{
double overDraft = 5000;
public CheckingAccount(int newID, double newBalance, double interestRate) {
super(newID, newBalance, interestRate);
}
public double getOverdraft() {
return overDraft;
}
public void setOverdraft(double overdraft) {
overDraft = 5000;
}
public double withdraw(double withdrawAmount){
double balance = getbalance();
if(balance - withdrawAmount >= -overDraft){
return super.withdraw(withdrawAmount);
}
else{
System.out.println("reach overdraf limit!");
setBalance(-overDraft);
return overDraft + getbalance();
}
}
#Override
public String toString() {
return "Account ID: " + id + "\nBalance: " + balance + "\nAnnual Interest rate: "
+ annualInterestRate + "\nDate of the Account Creation:" + dateCreated;
}
}
TESTACCOUNT CLASS
import java.util.*;
public class TestAccount {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int accID = 0;
double balance = 0;
double intRate = 0;
double withDraw = 0;
double Deposit = 0;
//savings account
System.out.println("Please enter the ID of the Savings Account: ");
accID = scan.nextInt();
scan.nextLine();
System.out.println("Please enter the initial Balance of the Savings Account: ");
balance = scan.nextDouble();
scan.nextLine();
System.out.println("Please enter the Interest Rate of the Savings Account: ");
intRate = scan.nextDouble();
scan.nextLine();
SavingAccount s = new SavingAccount(accID, balance, intRate);
System.out.println("Please enter an amount you would like to Withdraw from the Savings Account: ");
withDraw = scan.nextDouble();
s.withdraw(withDraw);
System.out.println("Please enter an amount you would like to Deposit into the Savings Account: ");
Deposit = scan.nextDouble();
s.deposit(Deposit);
System.out.println("\nSavings Account Status:\n" + s);
//Checking account
System.out.println("\nPlease enter the ID of the Checking Account: ");
accID = scan.nextInt();
scan.nextLine();
System.out.println("Please enter the initial Balance of the Checking Account: ");
balance = scan.nextDouble();
scan.nextLine();
System.out.println("Please enter the Interest Rate of the Checking Account: ");
intRate = scan.nextDouble();
scan.nextLine();
CheckingAccount c = new CheckingAccount(accID, balance, intRate);
System.out.println("Please enter an amount you would like to Withdraw from the Checking Account: ");
withDraw = scan.nextDouble();
c.withdraw(withDraw);
System.out.println("Please enter an amount you would like to Deposit into the Checking Account: ");
Deposit = scan.nextDouble();
c.deposit(Deposit);
System.out.println("\nChecking Account Status:\n" + c);
}
}
Also, is there anything else you would change to make the program better?
//two overload method to make a deposit from account
public void deposit(double depositAmount) {
balance += depositAmount;
}
public void deposit(int depositAmount) {
balance += depositAmount;
}
Yes, these are overloaded methods. You did it correctly.

Prompt for the program to end

I need to write a program for my CIS class, I feel I have the majority set up. Being 95%, To sum it all up simply. I have to write a program that prompts the user to input their name, pay rate, hours worked. It then takes the data, calculates the gross pay, then subtracts the tax, then prints it all to the screen. The program should allow multiple users to add data for however number of employee's, which forces me to believe I need to set a value they must enter to end the program. Problem is I am regrettably stumped on how to code it so when the value is entered, the program ends. I'm almost certain a while loop is needed, but any sort of feedback would be much appreciated.
package program1;
import java.util.*;
public class Program1 {
static Scanner console = new Scanner (System.in);
public static void main(String[] args) {
String firstName, lastName ;
double payRate;
int hoursWorked;
double netPay;
double grossPay;
String formatNet;
System.out.println("Please enter the employee's name. (Enter a -1 when finished): ") ;
firstName = console.nextLine();
lastName = console.nextLine();
System.out.println("Please enter the employee's pay rate. ");
payRate = console.nextDouble();
System.out.println("Please enter the employee's hours worked. ");
hoursWorked = console.nextInt();
if(hoursWorked > 40)
{
grossPay = payRate * hoursWorked * 1.5;
}
else
{
grossPay = payRate * hoursWorked;
}
netPay = grossPay - (grossPay * .15);
formatNet = String.format("%.2f", netPay);
System.out.println(firstName +" "+ lastName + "'s net pay is " + formatNet);
}
}
Yes, you need a loop. Try this code below.
Also note the presence of console.nextLine(); after
console.nextDouble(); and console.nextInt();.
public static void main(String[] args) {
String firstName, lastName;
double payRate;
int hoursWorked;
double netPay;
double grossPay;
String formatNet;
while (true){
System.out.println("Please enter the employee's name. (Enter a -1 when finished): ");
firstName = console.nextLine();
if ("-1".equals(firstName.trim())) break;
lastName = console.nextLine();
System.out.println("Please enter the employee's pay rate. ");
payRate = console.nextDouble();
console.nextLine();
System.out.println("Please enter the employee's hours worked. ");
hoursWorked = console.nextInt();
console.nextLine();
if (hoursWorked > 40) {
grossPay = payRate * hoursWorked * 1.5;
} else {
grossPay = payRate * hoursWorked;
}
netPay = grossPay - (grossPay * .15);
formatNet = String.format("%.2f", netPay);
System.out.println(firstName + " " + lastName + "'s net pay is " + formatNet);
}
}
Use do while loop and by using some condition you can terminate the loop like you can prompt user for "Do you want to continue(y/n)" and depending upon value you can iterate again.
EDIT
do
{
//your code goes here
System.out.println("Do you want to continue(y/n)?");
isContinue = console.next();
}while(isContinue = "Y" || isContinue = "y")
you can use break statement after checking firstname is -1 in if condition
Here is a solution. I threw in some Object-Orientation, method extraction and resource management to always close the Scanner after use.
import java.util.Scanner;
public class Program1 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
try {
do {
enterEmployee(console);
System.out.println("Another employee? (q to quit)");
} while (!"q".equals(console.nextLine()));
} finally {
console.close();
}
}
private static void enterEmployee(Scanner console) {
Employee employee = new Employee();
System.out.println("Please enter the employee's first name: ");
employee.setFirstName(console.nextLine());
System.out.println("Please enter the employee's last name: ");
employee.setLastName(console.nextLine());
System.out.println("Please enter the employee's pay rate: ");
employee.setPayRate(console.nextDouble());
console.nextLine();
System.out.println("Please enter the employee's hours worked: ");
employee.setHoursWorked(console.nextInt());
console.nextLine();
System.out.println(employee + "'s net pay is " + String.format("%.2f", employee.getNetPay()));
}
public static class Employee {
private String firstName;
private String lastName;
private double payRate;
private int hoursWorked;
private double netPay;
private double grossPay;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public double getPayRate() {
return payRate;
}
public void setPayRate(double payRate) {
this.payRate = payRate;
}
public int getHoursWorked() {
return hoursWorked;
}
public void setHoursWorked(int hoursWorked) {
this.hoursWorked = hoursWorked;
if (hoursWorked > 40) {
grossPay = payRate * hoursWorked * 1.5;
} else {
grossPay = payRate * hoursWorked;
}
netPay = grossPay - (grossPay * .15);
}
public double getNetPay() {
return netPay;
}
public double getGrossPay() {
return grossPay;
}
#Override
public String toString() {
return firstName + " " + lastName;
}
}
}

Java program not outputting correctly

I'm having a little bit of trouble with my code that I can't seem to figure out. Whenever I run this, it prints "Customer is null" instead of inserting their name. It also always calculates all tax as 0 (something wrong with my if statement?).
Is there any chance you guys can spot the issue? It seems as though everything else works correctly. (Wrote methods in Customer class, calling them in TestCustomer class, and the instructions are at the end of the post).
Thank you for anyone who takes the time to read this and attempt to help. Sorry for so much information, I just have no clue what is causing this, so I figured I'd include everything.
Customer class
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Customer {
public static double taxRate = 0.00;
public static double saleRate = 0.00;
String customerName;
double listSaleAmount;
double saleDiscount = 0;
double netSaleAmount;
double taxAmount;
double saleTotal;
boolean taxable;
public double total;
public Customer (String customerName, boolean taxable) {
}
public void calculateTax () {
saleDiscount = listSaleAmount*(saleRate/100);
netSaleAmount = listSaleAmount-saleDiscount;
if (taxable = true){
taxAmount = netSaleAmount*(taxRate/100);
}
else{
taxAmount = 0;
}
saleTotal = netSaleAmount + taxAmount;
total += saleTotal;
}
public void printRecord () {
System.out.println("Customer is " + customerName);
System.out.println("Sale amount is $" + listSaleAmount);
System.out.println("Discount amount is $" + saleDiscount);
System.out.println("Net Sale Amount is $" + netSaleAmount);
System.out.println("Tax amount is $" + taxAmount);
System.out.println("Total Sale Amount is $" + saleTotal);
System.out.println(" ");
}
public static void changeTaxAmount () {
Scanner input = new Scanner(System.in);
double userTaxAmount = Double.parseDouble(JOptionPane.showInputDialog("What is the Tax Rate? (8.25 & 8.50 for testing)"));
taxRate = userTaxAmount;
}
public static void changeSaleRate () {
Scanner input = new Scanner(System.in);
double userSaleAmount = Double.parseDouble(JOptionPane.showInputDialog("What is the Sale Discount Rate? (0.00 & 7.50 for testing)"));
saleRate= userSaleAmount;
}
public static void printTaxRate() {
System.out.println("Tax Rate is " + taxRate + "%.");
}
public static void printSaleRate() {
System.out.println("The Sale Rate is " + saleRate + ".");
System.out.println(" ");
}
}
TestCustomer class
public class TestCustomer {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Customer customer1 = new Customer("Annie Smith", true);
Customer customer2 = new Customer("Bob Wilson", false);
Customer.changeTaxAmount();
Customer.printTaxRate();
Customer.changeSaleRate();
Customer.printSaleRate();
customer1.listSaleAmount = 65.00;
customer2.listSaleAmount = 52.00;
customer1.calculateTax();
customer1.printRecord();
customer2.calculateTax();
customer2.printRecord();
Customer.changeTaxAmount();
Customer.printTaxRate();
Customer.changeSaleRate();
Customer.printSaleRate();
customer1.listSaleAmount = 84.00;
customer2.listSaleAmount = 105.00;
customer1.calculateTax();
customer1.printRecord();
customer2.calculateTax();
customer2.printRecord();
double total2 = customer1.total + customer2.total;
System.out.println("The total of all sales is $" + total2);
}
}
Assignment sheet (Not worrying about printing to a file right now, just want the main mechanics to work)
Also, thank you to those of you who helped me with my last question on this project. You helped a lot.
In your constructor
public Customer (String customerName, boolean taxable) {
}
You are passed in parameters, but you never assign them to your class fields.
try
public Customer (String customerName, boolean taxable) {
this.customerName = customerName;
this.taxable = taxable;
}
You have to define your constructor in customer class to set values of customerName and texable class level variables:
public Customer (String customerName, boolean taxable) {
this.customerName = customerName;
this.taxable = taxable;
}
Also, there seems to be problem with the below if condition:
if (taxable = true){
You should use == operator for comparing:
if (taxable == true) {
Actually, you don't need to compare it. Just use:
if (taxable) {
Your constructor in Customer class should assign the name and taxable value to Customer data member.
public Customer (String customerName, boolean taxable) {
this.customerName = customerName;
this.taxable = taxable;
}
Instead of using if (taxable = true), simply use if (taxable).

I am having trouble with the program skipping over the first input when looping. Please help

Ok, so I had to modify my already working program to use 2 separate classes...one to perform the task and one to store info. Once it does the first calculation and it gets to the second entry, it skips over employee name. Why? Please help. Here is the code:
package payroll_program_3;
import java.util.Scanner;
public class payroll_program_3
{
public static void main(String[] args)
{
Scanner input = new Scanner( System.in );
employee_info theEmployee = new employee_info();
String eName = "";
double Hours = 0.0;
double Rate = 0.0;
while(true)
{
System.out.print("\nEnter Employee's Name: ");
eName = input.nextLine();
theEmployee.setName(eName);
if (eName.equalsIgnoreCase("stop"))
{ return;
}
System.out.print("\nEnter Employee's Hours Worked: ");
Hours = input.nextDouble();
theEmployee.setHours(Hours);
while (Hours <0) { System.out.printf("Hours cannot be negative\n");
System.out.printf("Please enter hours worked\n");
Hours = input.nextDouble();
theEmployee.setHours(Hours);
}
System.out.print("\nEnter Employee's Rate of Pay: ");
Rate = input.nextDouble();
theEmployee.setRate(Rate);
while (Rate <0) { System.out.printf("Pay rate cannot be negative\n");
System.out.printf("Please enter hourly rate\n");
Rate = input.nextDouble();
theEmployee.setRate(Rate);
}
System.out.print("\n Employee Name: " + theEmployee.getName());
System.out.print("\n Employee Hours Worked: " + theEmployee.getHours());
System.out.print("\n Employee Rate of Pay: " + theEmployee.getRate() + "\n\n");
System.out.printf("\n %s's Gross Pay: $%.2f\n\n\n", theEmployee.getName(), theEmployee.calculatePay());
}
}
}
PART 2:
package payroll_program_3;
public class employee_info
{
String employeeName;
double employeeRate;
double employeeHours;
public employee_info()
{
employeeName = "";
employeeRate = 0;
employeeHours = 0;
}
public void setName(String name)
{
employeeName = name;
}
public void setRate(double rate)
{
employeeRate = rate;
}
public void setHours(double hours)
{
employeeHours = hours;
}
public String getName()
{
return employeeName;
}
public double getRate()
{
return employeeRate;
}
public double getHours()
{
return employeeHours;
}
public double calculatePay()
{
return (employeeRate * employeeHours);
}
}
There are two places where an infinite loop can occurring, as Hours & Rate are not changing inside of them.
while (Hours <0)
{
System.out.printf("Hours cannot be negative\n");
System.out.printf("Please enter hours worked\n");
}
while (Rate <0)
{
System.out.printf("Pay rate cannot be negative\n");
System.out.printf("Please enter hourly rate\n");
}
Haven't read all the code, but it is likely this needs to be an if statement containing a continue.
You need hours= input.next double to change hour var so it fails the while condition

Categories