Payroll Array Java Calculation - java

Hello guys, this is my first time i post something in here and i just started learning java. This is my assignment and i need to write a payroll code with array. However, i dont understand why i cant get it to work. Somehow, it only calculate the last employee, the first and second are not included. If you guys can help i'd appreciate it. Thank you!
public class ArrayIG
{
public static void main(String[] args)
{
final int NUM_EMPLOYEES = 3;
//creating array
int[]hours = new int[NUM_EMPLOYEES];
int[] employeeID = {5678459, 4520125, 7895122};
double payRate;
double wages = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your " + NUM_EMPLOYEES + " employees work hours and pay rate:");
//get the hours
for (int i = 0; i < NUM_EMPLOYEES; i++)
{
System.out.print("Employee #" + employeeID[i] + ": ");
hours[i] = keyboard.nextInt();
//get the hourly pay rate
System.out.print("Enter the pay rate: ");
payRate = keyboard.nextDouble();
wages = hours[i] * payRate;
}
//display wages
System.out.println("The hours and pay rates you entered are:");
for(int i = 0; i < NUM_EMPLOYEES; i++)
{
System.out.printf("The total wages for Employee #%d is $%.2f\n", employeeID[i], wages);
}
}
}
MY OUTPUT:
Enter your 3 employees work hours and pay rate:
Employee #5678459: 35
Enter the pay rate: 21
Employee #4520125: 37
Enter the pay rate: 18.5
Employee #7895122: 39
Enter the pay rate: 37.25
The hours and pay rates you entered are:
The total wages for Employee #5678459 is $1452.75
The total wages for Employee #4520125 is $1452.75
The total wages for Employee #7895122 is $1452.75

Either create an array of wages or calculate wages in loop where wages are being print. And you should do assignments on your own 😀

You're collecting 3 different hours but only storing them in one value. The same for the wages. What happens when you store them as an array?
import java.util.Scanner;
public class ArrayIG
{
public static void main(String[] args)
{
final int NUM_EMPLOYEES = 3;
//creating array
int[] hours = new int[NUM_EMPLOYEES];
int[] employeeID = {5678459, 4520125, 7895122};
double[] payRate = new double[NUM_EMPLOYEES];
double[] wages = new double[NUM_EMPLOYEES];
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your " + NUM_EMPLOYEES + " employees work hours and pay rate:");
//get the hours
for (int i = 0; i < NUM_EMPLOYEES; i++)
{
System.out.print("Employee #" + employeeID[i] + ": ");
hours[i] = keyboard.nextInt();
//get the hourly pay rate
System.out.print("Enter the pay rate: ");
payRate[i] = keyboard.nextDouble();
wages[i] = hours[i] * payRate[i];
}
//display wages
System.out.println("The hours and pay rates you entered are:");
for(int i = 0; i < NUM_EMPLOYEES; i++)
{
System.out.printf("The total wages for Employee #%d is $%.2f\n", employeeID[i], wages[i]);
}
}
}

You have 3 employees -> 3 wages.
But currently you're using only one variable to hold the wage: double wages = 0;
Hence its value is replaced for every loop.
You should create an array of length 3 to store the wages:
and in your loop, replace
wages = hours[i] * payRate;
With
wages[i] = hours[i] * payRate;
And print:
System.out.printf("The total wages for Employee #%d is $%.2f\n", employeeID[i], wages[i]);

You are setting the wage rate at each iteration. I.e. you are only ever recording a single state of wages. Then you are iterating and displaying that one wages variable, which will always be the last calculation.
Store each "wages" value in an array like you have done with hours and you should resolve your issue.

Related

A java program that displays weekly payroll for 5 employees (error in desired output)

My coding is based on this question:
screenshot of the question
And this is what I've coded and it's completed but I have an error in the desired output.
package assignment_2;
import java.util.Scanner;
public class Assignment_2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner (System.in);
String employeeName[] = new String[5];
int employeeID[] = new int[5];
int payStatus[] = new int[5];
double Grosspay[] = new double [5];
int workHours[] = new int[5];
double payRateperhour[] = new double [5];
double incomeTax[] = new double [5];
double netPay[] = new double [5];
System.out.println("Enter 5 employee details.");
for (int i = 0; i < 5; i++) {
String nextLine = input.nextLine(); //skip whitespace error
System.out.print("Enter Employee " + (i+1) + " name: "); //prompt user input for employee name
employeeName[i] = input.nextLine();
System.out.print("Enter Employee " + (i+1) + " ID: "); //prompt user input for employee ID
employeeID[i] = input.nextInt();
System.out.print("Enter Employee " + (i+1) + " pay status (1 = Salary or 2 = Hourly): "); //prompt user input for employee paid by salary or hourly?
payStatus[i] = input.nextInt();
if (payStatus[i] == 1){ //pay by salary user input
System.out.print("Enter employee gross pay(RM): ");
Grosspay[i] = input.nextDouble();
System.out.print("Enter employee work hours per week: ");
workHours[i] = input.nextInt();
} else { //pay by hourly user input
System.out.print("Enter employee pay rate per hour(RM): ");
payRateperhour[i] = input.nextDouble();
System.out.print("Enter employee work hours per week: ");
workHours[i] = input.nextInt();
//calculate overtime pay
if (workHours[i] > 40) {
Grosspay[i] = (40 * payRateperhour[i]) + 1.5 * (workHours[i] - 40) * payRateperhour[i];
} else Grosspay[i] = workHours[i] * payRateperhour[i];
}
//calculate income tax
if (Grosspay[i] > 0.00 || Grosspay[i] < 999.99) {
incomeTax[i] = (8 /100) * Grosspay[i];
} else if (Grosspay[i] > 500.00 || Grosspay[i] < 999.99) {
incomeTax[i] = (10 /100) * Grosspay[i];
} else if (Grosspay[i] > 1000.00) {
incomeTax[i] = (15 /100) * Grosspay[i];
} else
//calculate net pay
netPay[i] = Grosspay[i] - incomeTax[i];
}
//Display employee details and weekly salary
System.out.print("\n\n\t\tPrint Daily Company (PDC)\n\t\t Weekly Payroll Data\n");
System.out.println("----------------------------------------------------------------");
System.out.println(" Name\t\tID#\tGross Pay\tTax\tNet Pay");
for (int i = 0; i < 5; i++) {
System.out.println(employeeName[i] + "\t" + employeeID[i] + "\t" + Grosspay[i] + "\t" + incomeTax[i] + "\t" + netPay[i]);
}
}
}
My error is that it does not calculate the income tax. In the output it shows 0.00. And the net pay is being outputted the same amount as the gross pay. And one of the outputs from a given sample I keyed in my program showed more than 2 decimal places unlike the rest of the outputs.
P.s: I also didn't know how to fix the error of whitespace os skipping an input line. So I just inserted String nextLine = input.nextLine(); //skip whitespace error before all the user inputs. (If anyone can help me with that or teach/show me a smooth output, that'd be great)
Thank you in advance.
Below is how my output looks like in case anyone was wondering.
screenshot of output
[UPDATE]:
This is the updated output for my program. enter image description here My net pay isn't working and so as the decimal point value. Still in need of help.
Thank you in advance.
So this little "problem" is not that easy to catch.
But in essence, Java tricked you by rounding numbers. Every time you used (8 / 100) or any other of the calculations for the income tax, java just rounded them to 0, because integer / integer is interpreted as integer result. The easiest way to fix it, is just to add .0 to each 100.
if (Grosspay[i] > 0.00 || Grosspay[i] < 999.99) {
incomeTax[i] = (8 / 100.0) * Grosspay[i];
} else if (Grosspay[i] > 500.00 || Grosspay[i] < 999.99) {
incomeTax[i] = (10 / 100.0) * Grosspay[i];
} else if (Grosspay[i] > 1000.00) {
incomeTax[i] = (15 / 100.0) * Grosspay[i];
}
This should work.

Yearly price increase loop? Stuck on nested loop

I'm trying to write a program that uses scanner keyboard to input these values and uses a loop to have them increase (2006-2010, year-year, & an increase in price, 90-100, etc.)
The output is supposed to look like this:
Enter the current Mars bar price in cents: 90
Enter the expected yearly price increase: 15
Enter the start year: 2006
Enter the end year: 2010
Price in 2006: 90 cents
Price in 2007: 105 cents
Price in 2008: 120 cents
Price in 2009: 135 cents
Price in 2010: 150 cents
This is the code I have so far:
import java.util.Scanner;
public class Problem_2 {
public static void main(String[] args) {
// TODO, add your application code
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the current Mars bar price in cents: ");
int m = keyboard.nextInt();
System.out.print("Enter the expected yearly price increase: ");
int p = keyboard.nextInt();
int a = m+p;
int count = 1;
System.out.print("Enter the start year: ");
int start = keyboard.nextInt();
System.out.print("Enter the end year: ");
int end = keyboard.nextInt();
for (int i = start; i <= end; i++){
System.out.print("Price in " +i+ ": " +m);start++;
}
}
and it allows me to have the year increasing to the set amount (again like 2006-2010) but I'm stuck on having the price increase along with it by the set amount, I assume it would be a nested loop but I'm not sure how to write it.
(I assume a nested loop because that's what we're learning right now.)
If anyone has any advice on what I could write, I'd really appreciate it!
I think you just need to sum the expected yearly price increase to the current price in each iteration of your loop, it'd be something like this:
import java.util.Scanner;
public class Problem_2 {
public static void main(String[] args) {
// TODO, add your application code
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the current Mars bar price in cents: ");
int m = keyboard.nextInt();
System.out.print("Enter the expected yearly price increase: ");
int p = keyboard.nextInt();
int count = 1;
System.out.print("Enter the start year: ");
int start = keyboard.nextInt();
System.out.print("Enter the end year: ");
int end = keyboard.nextInt();
for (int i = start; i <= end; i++){
System.out.print("Price in " +i+ ": " +m);
m += p; // sum expected price for each iteration
}
}

copying arrays from a method to main method

I am asked to write a program that requires three arrays in the main method. The program is supposed to calculate gross wages for given employee ids from user input of the pay rate and hours also from user input. Also, it is asking me to write a method calculateWages with three array parameters: hours, payRate, and wages, which calculates and stores the wages for each employee by multiplying the corresponding hours and pay rates.
Your program should display each employee number and ask the user to enter that employee's hours and pay rate. After getting the hours and pay rates for all employees, your program should call calculateWages. Next, your program should display each employee's identification number and gross wages. Note: the number of employees and the minimum wage should both be named constants.
public static void main(String[] args)
{
double[] employeeID = {5658845, 4520125, 7895122, 8777541, 8451277,1302850, 7580489}; //Employee IDs of which we are calculating gross wages for
double[] payRate = new double[7];
double[] employeeWages = new double[7];
double[] employeeHours = new double[7];
Scanner keyboard = new Scanner(System.in); //Needed for keyboard input
for (int i = 0; i<employeeID.length; i++)
{
System.out.println("Employee ID: " + employeeID[i]);
System.out.print("Enter the number of hours worked: ");
employeeHours[i]=keyboard.nextDouble();
//Get and validate hours from user.
while(employeeHours[i]<0)
{
System.out.println("Error. Hours worked must not be negative.");
System.out.print("Please enter hours worked: ");
employeeHours[i]=keyboard.nextDouble();
}
//Get and validate pay rate from employees.
System.out.print("Enter the pay rate of employee: ");
payRate[i]=keyboard.nextDouble();
while(payRate[i]<10.24)
{
System.out.println("Error. Minimum pay rate must be at least $10.24");
System.out.print("Please enter the pay rate: ");
payRate[i]=keyboard.nextDouble();
}
}
calculateWages(employeeWages, employeeHours, payRate);
System.out.println("Gross Wages:");
System.out.println();
for(int i=0;i<employeeID.length;i++)
{
System.out.printf("%-9d%-7s",employeeID[i],employeeWages[i]);
}
}
public static String[] calculateWages(double[] employeeWages, double[] inputHours,double[] payRate)
{
String[] formatWage = new String[7];
DecimalFormat formatter = new DecimalFormat("$###.00");
for(int i = 1;i<employeeWages.length;i++)
{
employeeWages[i]=inputHours[i]*payRate[i];
formatWage[i]=formatter.format(employeeWages[i]);
}
return formatWage;
}
}
calculateWages is returning an array so set an array equal to it
String [] result = calculateWages(employeeWages, employeeHours, payRate);

Need to pull commission rate from one array into the output

I'm in a beginners Java class and am having trouble with getting this to work. I need to get my program to pull the commission rate from one array into the output. Everything else seems to be working but it won't calculate the commission and I'm not sure what I am missing. Any help would be wonderful!
public class Annualwages extends salesperson
{
/** #param args the command line arguments */
public static void main(String[] args)
{ //begins the main method
salesperson sp = new salesperson();
sp.saleInformation();
System.out.println("You entered the following:");
System.out.println();
for (int index = 0; index < sp.salesP.length; index++)
{
System.out.println("Sales Person " + (index + 1));
System.out.println(" Name: "
+ sp.salesP[index]);
System.out.println(" Total Annual Sales: "
+ sp.sales[index]);
System.out.println(" Base Salary is: " + sp.SALARY);
System.out.println(" Annual Commission is: "
+ sp.comm[index]);
System.out.println(" Total Annual Compensation is: "
+ sp.totalWages );
System.out.println();
}
} // ends main method
} //ends annual wages class
package annualwages;
import java.util.Scanner;
class salesperson { //begins salesperson class
protected String name;
protected String[] salesP; // To reference an array of sales people
protected double[] sales; // references an array for sales achieved
protected double[] comm; // references an array for commission rate
protected int numSales; // Number of sales people & sales achieved
protected final double COMMISSION=0.15; //Sets a fixed variable for commission earned
protected final double SALARY=50000; //Sets a fixed variable for Salary earned
protected final double SALESTARGET=120000; //Sets a fixed variable for the sales target
protected double totalSales, totalWages, actualCommission, accelFactor=1.25;
public void saleInformation()
{ //begins saleInformation method
// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);
//Get number of sales people
System.out.print("How many sales people do you want to compare? ");
numSales = keyboard.nextInt();
// Creates an array to hold number of sales people.
salesP = new String [numSales];
//Gets the names of the sales people.
for (int index = 0; index < salesP.length; index++)
{
System.out.print("Enter name of sales person "
+ (index + 1) + ": ");
salesP[index] = keyboard.next();
}
//creates an array to hold amoount in sales achieved
sales = new double[numSales];
// gets the amount in sales that each sales person has achieved annually
for (int index = 0; index < sales.length; index++)
{
System.out.print("Enter amount in sales achieved per person annually "
+ (index + 1) + ": ");
sales[index] = keyboard.nextDouble();
}
// creates an array to hold the commission rate
comm = new double [numSales];
//Sales incentive begins at a minimum at $96,000 in sales.
//if less than, then no commission is earned
for (int index = 0; index < comm.length; index ++)
{
if (sales.length <= 96000)
{
actualCommission=0;
}
// Sales incentive with $96,000 or more earns 15% commission
else if ((sales.length > 96000) && (sales.length < SALESTARGET ))
{
actualCommission=COMMISSION;
}
//Sales incentive increases if the sales person earns more than $120,000
//in sales with the acceleration factor of 1.25
else
{
actualCommission=COMMISSION*accelFactor;
}
}
//Calculates total sales by multiplying sales and commission
totalSales = sales.length* comm.length;
//Calculates total wages by adding salary to total sales
totalWages = SALARY + totalSales;
} //ends saleInformation method
} //ends salesperson class
You have a few errors.
You're not assigning any value to comm[index] when you calculate the commission. Instead of using the actualCommission variable (which you never actually display), just assign directly to comm[index].
The variable sales.length is unlikely ever to be 96000 or more, since it's the number of sales you're putting in. So the first if condition is going to return true every time, and you'll end up setting the commission to zero. Perhaps you meant to write if (sales[index] <= 96000) instead. Similarly for the other comparisons involving sales.length.

My methods aren't bringing the data along with it (beginner) [duplicate]

This question already has answers here:
Division in Java always results in zero (0)? [duplicate]
(3 answers)
Closed 8 years ago.
This is my first CS project ever. After creating my method, I ran the code to see if it works so far, everything works correctly but it does not actually do the math inside the method. Been working on this forever and can't find the bug. Any help would be great. Its due tomorrow lol.
public static void main(String[] args) {
int numberOfStudents = 0;
int total = 0;
int value = 0;
int creditHours;
double tuition;
int classesMissed;
System.out.println("Tuition Wasted Based on Student Absences and its effect on GPA.");
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the number of students to consider: ");
value = keyboard.nextInt();
while (value >= 5)
{
if (value > 5)
System.out.println("Number of students must be between 1 and 5");
System.out.print("Please re-enter a value number of students to consider: ");
value = keyboard.nextInt();
}
System.out.print("Enter the student ID for student 1: ");
value = keyboard.nextInt();
System.out.print("For how many credit hours is the student registered: ");
creditHours = keyboard.nextInt();
System.out.print("Enter the amount of the tuition for the semester: ");
tuition = keyboard.nextDouble();
System.out.print("Enter the average number of classes the student misses in a week: ");
classesMissed = keyboard.nextInt();
while (classesMissed > creditHours)
{
if (classesMissed > creditHours)
System.out.print("That is not possible, please re-enter the number of classes missed in a week: ");
classesMissed = keyboard.nextInt();
}
DetermineWastedTuition(creditHours, tuition, classesMissed);
}
public static void DetermineWastedTuition(int creditHours, double tuition, int classesMissed){
double weeklyTuition;
weeklyTuition = tuition / 10;
double weeklyTuitionWasted;
weeklyTuitionWasted = weeklyTuition *(classesMissed / creditHours);
double semesterWasted;
semesterWasted = weeklyTuitionWasted * 16;
System.out.println("Tuition money wasted each week is " + weeklyTuitionWasted);
System.out.println("Tuition money wasted each semester is " + semesterWasted);
}
With the sample output as:
Tuition Wasted Based on Student Absences and its effect on GPA.
Enter the number of students to consider: 1
Enter the student ID for student 1: 1234555
For how many credit hours is the student registered: 15
Enter the amount of the tuition for the semester: 7500
Enter the average number of classes the student misses in a week: 2
Tuition money wasted each week is 0.0
Tuition money wasted each semester is 0.0
The following calculation :
weeklyTuitionWasted = weeklyTuition * (classesMissed / creditHours);
would return 0.0 if classesMissed < creditHours, since you are dividing two int variables, and therefore the result will be an int.
Change it to :
weeklyTuitionWasted = weeklyTuition * ((double) classesMissed / creditHours);

Categories