I'm making a payroll using Java. Why am I getting the wrong net pay if my mathematical formulas seem correct?

Viewed 94

I'm making a payroll calculator. The first person worked 38.00 hours with a pay rate of $8.75. The second person worked 46.50 hours with a pay rate of $17.00. It's obvious the second person worked overtime. I'm experiencing issues when calculating the net pay as well as the gross pay. The second person's net pay should be $718.89. I keep getting $140.89. The issues only happen if the person works overtime (>40). Is there a problem with my if statement? I'd like some advice. I've been learning Java for 2 weeks now, excuse the mistakes.

package com.company;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        final byte PERCENT = 15;
        // Tax is 15%
        final float taxRate = PERCENT / (float) 100;

        Scanner scanner = new Scanner(System.in);
        System.out.print("First Name: ");
        String firstName = scanner.next().trim();
        System.out.print("Last Name: ");
        String lastName = scanner.next().trim();
        System.out.println(lastName + ", " + firstName);
        System.out.print("Pay Rate: ");
        float payRate = scanner.nextFloat();
        System.out.print("Hours Worked: ");
        float totalHours = scanner.nextFloat();

        // regular hours = total hours if less than 40
        // overtime = total hours - 40

        float regularPay = 0;
        if (totalHours <= 40) {
            regularPay = totalHours * payRate;
        }
        float overTimePay = 0;
        if (totalHours > 40) {
            overTimePay = (float) ((totalHours - 40) * 1.5 * payRate);
        }
        final double grossPay = (double) regularPay + (double) overTimePay;
        System.out.println("Gross Pay: " + (Math.round(grossPay * 100.0) / 100.0));
        final double taxAmount = grossPay * taxRate;
        System.out.println("Tax Amount: " + (Math.round(taxAmount * 100.0) / 100.0));
        final double netPay = grossPay - taxAmount;
        System.out.println("Net Pay: " + (Math.round(netPay * 100.0) / 100.0));
    }
}
2 Answers

your regularPay variable is only being recorded if hours<=40. You need to put something in your second if statement to set your regularPay variable. You probably want something like:

regularPay = 40*payRate;

Include this in your second if statement

if totalHours > 40, regularPay will be 0 in your code. you should change the condition to something like this.

  • if totalHours > 40, first calculate regularPay for 40 hours
  • overtimepay should be remaining hours (totalhours -40)
Related