payroll : adding multiple array values - java

The question is to create a program that asks the user to input how many employees. Then with each employee, a name, hour pay rate, hours worked is entered. the results of the employee pay, overtime pay and total pay is calculated.
My dilemma is how to find the total of all the pays. all employees pay, all employees overtime pay and all employees total pay
ex. user input: 2 employees (creates two arrays)
two inputs(name, rate, hours worked) will be entered
two results (pay, overtime pay, total pay) will be calculated
how do you add the pays, the overtime pays and total pays from both employees?
this is the code ive come up with, but it needs work
import java.util.Scanner;
public class paycheck {
public static void main(String[] args)
{
Scanner input= new Scanner(System.in);
System.out.print("Enter number of Employees: ");
int numberOfEmp= input.nextInt();
int[] arrayList= new int[numberOfEmp];
for (int i = 0; i < arrayList.length; i++){
System.out.print("Enter Employee Name: ");
String empName= input.next();
System.out.print("Enter hourly rate: ");
int rate= input.nextInt();
System.out.print("Enter hours worked: ");
int hours=input.nextInt();
if (hours >=40)
{
double regPay= hours * rate;
double otPay = (hours-40) *(rate*1.5);
double totalPay= regPay + otPay;
System.out.print("\nEmployee name: " + empName+"\n Regular pay: " + regPay +"\n Overtime pay: " + otPay+ "\n Total pay: " + totalPay+ "\n"+ "\n");
}
else
{
double regPay= hours * rate;
double otPay =0;
double totalPay= regPay + otPay;
System.out.print("\nEmployee name: " + empName+ "\n Regular pay: " + regPay +"\n Overtime pay: " + otPay+ "\n Total pay: " + totalPay+ "\n"+ "\n");
}
}
}
}

why dont you keep three different variables , say allsalary , allovertime , allpay and keep on adding whenever any new employee is entered .

Create an employee object that holds the values you want to track.
Create an ArrayList of employees.
Create a while loop that allows the user to input a employee's info, and then asks the user if they would like to continue or stop. If they want to stop exit the loop and print your data.
If you create an employee object, you might want to give it a few static variables to keep track of total_pay, total_ot_pay, and other "totals" you want to track.

Related

How would I display a shape in JOptionPane.showMessageDialog() in Processing?

Part of the requirement is to replicate the bar graph in https://imgur.com/a/Gx2XOql
I tried this to see if I could rectangle in the dialogue window (obviously it didn't work):
rectMode(CENTER);
// Alberta
if ( prov_id.equals("AB") || prov_id.equals("ab"))
{
if (gross_income>=0&&gross_income<=40000)
{
tax_rate=0.25;
JOptionPane.showMessageDialog(frame,"Province: "+ prov_id + "\nGross Income: "+ gross_income + "\nTax Rate: "+ tax_rate+ "\nTax Amount: "+ tax_amount+"\nNet Income: "+ net_income + rect(10,10,10,10));
}
The rest of my code:
import javax.swing.JOptionPane;
//Input Variables
String prov_id = ""; //province_id will contain the user input for the province (E.g. 'AB').
float gross_income = 0; //gorss_income contains the user input for gross income (E.g. 30000).
//Output Variables:
//You will store the result of your analysis and calculations in these variables
float tax_rate = 0; //Variable tax_rate will hold the tax_rate percentage. You will assign a value for tax_rate based on the Taxable Income (Table 1) table given in the studio project document.
//The value of tax ranges between 0 to 1 (E.g. for Alberta, income of equal or less than $40000 tax = 0.25)
float net_income = 0; //Net income is calculated based on tax_rate. It is the take-home income after taxes are deducted.
//i.e. net_income = gross_income * (1 - tax_rate);
float tax_amount = 0; //tax amount is the amount of taxes paid based on gross income depending on the province.
//i.e. tax_amount = gross_income * tax_rate;
// prompt for and read the province id
prov_id = JOptionPane.showInputDialog("Please enter your province's two-letter abbreviation (e.g., AB for Alberta): ");
// prompt for and read the gross income
String answer = JOptionPane.showInputDialog("Please enter your taxable income: ");
//convert user input to folat
gross_income = Float.parseFloat(answer);
net_income=gross_income*(1-tax_rate);
tax_amount=gross_income*tax_rate;
rectMode(CENTER);
// Alberta
if ( prov_id.equals("AB") || prov_id.equals("ab"))
{
if (gross_income>=0&&gross_income<=40000)
{
tax_rate=0.25;
JOptionPane.showMessageDialog(frame,"Province: "+ prov_id + "\nGross Income: "+ gross_income + "\nTax Rate: "+ tax_rate+ "\nTax Amount: "+ tax_amount+"\nNet Income: "+ net_income);
}
}
The expected out put is supposed to be this: https://imgur.com/a/Gx2XOql
So far my code displays this: https://imgur.com/a/Gx2XOql
The window where the bar graphs are shown is Processing's not one from JOptionPane.showMessageDialog() since the window is named "TaxCalculator_kEY", which i assume is the name of the file, not "Message".

Having trouble with the math for a loan calculator program

This is a loan calculator program. I'm having trouble with the math. Everything else seems to be correct except for the value of the beginning balance after 2 months. Notice that the beginning balance of the 3rd month is different from the ending balance of the 2nd month. Same thing for the succeeding months. I've been trying to fix it but everything didn't work out. I need them to be the same so the ending balance of the last month will be 0.
This is a sample output of the program:
Personal Loan Payment Calculator
Enter a loan amount: 1000
Enter the loan term (months): 6
Enter the interest rate (% per year): 9
Loan Payment and Amortization Table
Months Beginning Monthly Principal Interest Ending
Balance Payment Paid Paid Balance
1 1000.00 171.07 163.57 7.50 836.43
2 836.43 171.07 164.80 6.27 671.64
3 670.41 171.07 166.04 5.03 504.37
4 501.88 171.07 167.30 3.76 334.57
5 330.78 171.07 168.59 2.48 162.19
6 157.06 171.07 169.89 1.18 -12.83
Summary:
========
Loan Amount: $1,000.00
Monthly Payment: $171.07
Number of Payments: 6
Total Interest Paid: $24.00
Annual Interest Rate: 9.00%
This is the program:
public class LoanCalculator {
public static void main(String[] args) {
System.out.println("Personal Loan Payment Calculator"); // print the name of the program
System.out.println("================================");
Scanner keyboard = new Scanner (System.in); // define a Scanner object attached to a keyboard
String badInput; // assign non-integer or non-double inputs to badInput
System.out.print("Enter a loan amount: "); // prompt the user to enter loan amount
while ( ! keyboard.hasNextDouble()) // is the first input value a double?
{
badInput = keyboard.next();
System.out.println("Error: expected a Double, encountered: " + badInput);
System.out.println("Please enter a loan amount in Double: ");
}
double loanAmount = keyboard.nextDouble(); // assign the first input to loanAmount
System.out.print("Enter the loan term (months): "); // prompt the user to enter number of months
while ( ! keyboard.hasNextInt()) // is the second input value an int?
{
badInput = keyboard.next();
System.out.println("Error: expected an Integer, encountered: " + badInput);
System.out.println("Please enter a loan term in Integer: ");
}
int loanTerm = keyboard.nextInt(); // assign the second input to loanTerm
System.out.print("Enter the interest rate (% per year): "); // prompt the user to enter the interest rate
while ( ! keyboard.hasNextDouble()) // is the first input value a double?
{
badInput = keyboard.next();
System.out.println("Error: expected an integer, encountered: " + badInput);
System.out.println("Please enter a loan amount in Double: ");
}
double interestRate = keyboard.nextDouble(); // assign the third input to interestRate
System.out.println(); // skip a line
System.out.println(" Loan Payment and Amortization Table");
System.out.printf("%s", "=============================================================");
System.out.println();
System.out.printf("%5s %10s %10s %10s %10s %10s", "Months" ,"Beginning", "Monhtly", "Principal", "Interest", "Ending");
System.out.println();
System.out.printf(" %5s %10s %10s %10s %10s %10s", "#","Balance", "Payment", "Paid", "Paid", "Balance");
System.out.println();
System.out.printf("%s ", "=============================================================");
System.out.println();
double monthlyRate = (interestRate / 100.0) / 12.0;
double monthlyPayment = (monthlyRate * loanAmount) / ( 1 - (Math.pow( 1 + monthlyRate, - loanTerm)));
double beginningBalance = loanAmount;
double interestPaid = beginningBalance * monthlyRate;
double principalPaid = monthlyPayment - interestPaid;
int total_interest_paid = 0;
for (int monthCount = 0 ; monthCount < loanTerm ; ++monthCount)
{
int months = 1 + monthCount;
beginningBalance = loanAmount - principalPaid * monthCount;
interestPaid = beginningBalance * monthlyRate;
principalPaid = monthlyPayment - interestPaid;
double endingBalance = beginningBalance - principalPaid;
System.out.printf(" %5d %10.2f %10.2f %10.2f %10.2f %10.2f\n", months, beginningBalance, monthlyPayment, principalPaid, interestPaid, endingBalance);
total_interest_paid += interestPaid;
}
System.out.printf("%s ", "=============================================================");
System.out.println();
NumberFormat currency = NumberFormat.getCurrencyInstance();
DecimalFormat percentFormat = new DecimalFormat ("0.00");
System.out.println("\nSummary:");
System.out.println("========");
System.out.println("Loan Amount: " + currency.format(loanAmount));
System.out.println("Monthly Payment: " + currency.format(monthlyPayment));
System.out.println("Number of Payments: " + loanTerm);
System.out.println("Total Interest Paid: " + currency.format(total_interest_paid));
System.out.println("Annual Interest Rate: " + percentFormat.format(interestRate) + "%");
}
}
The error is very simple:
beginningBalance = loanAmount - principalPaid * monthCount;
Remember that "principalPaid" increases every month. The total principal paid is not the last principalPaid * mouthCount but the sum of the principal paid in all months.
You could create a running total for principalPaid like you did for interest paid.
But it would be much easier to do beginningBalance = previous month endingBalance.

How can I make a user input 20 be read by the program as 20% or 0.20

This is the part where I ask the user to input the following.
Enter the item name: Shirt
Original price of the item: 700
Marked-up Percentage: 20
Sales Tax Rate: 7
Output:
Item to be sold : Shirt
Original price of the item: 700.00
Price after mark-up: 840.00
Sales tax: 58.80
Final price of item: 898.80
so my question is how can I make that 20 and 7 input be read by the program as percentages.
import java.util.*;
import javax.swing.*;
public class lab3 {
public static void main(String[] args) {
JOptionPane jo=new JOptionPane();
String item=jo.showInputDialog("Item to be sold: ");
double Oprice=Double.parseDouble(
jo.showInputDialog("Original price of the item: "));
double mup=Double.parseDouble(
jo.showInputDialog("Marked-up percentage: "));
double str=Double.parseDouble(
jo.showInputDialog("Sales Tax Rate: "));
double pamu=(Oprice*mup)+Oprice;
double ST=pamu*str;
double result=pamu+ST;
String hold= "\n| Item to be sold \t: "+item+"\t |"
+"\n| Original price of the item \t: "+Oprice+"\t |"
+"\n| Price after mark-up \t: "+pamu+"\t |"
+"\n| Sales Tax \t: "+ST+"\t |"
+"\n| Final price of the item \t: "+result+"\t |";
jo.showMessageDialog(null, new JTextArea(hold));
}
}
That is my actual code. sorry if its messy. like I said still new to this
Let's use Scanner for reading from user:
Scanner sc = new Scanner(System.in);
double percentage = 0.01 * sc.nextInt();
will do the trick.
double pamu = (Oprice*(mup/100)) + Oprice; // enter code here
double ST = pamu*(str/100) ;
double result = pamu+ST ;
I think this should work.
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter item name:");
String item;
keyboard.nextLine();
System.out.println("Original Price of item:");
double originalPrice;
keyboard.nextDouble();
System.out.println("Marked up percentage:");
double markedUpPercentage;
keyboard.nextDouble();
markedUpPercentage = markedUpPercentage/100; //this is what you want
System.out.println("Sales tax rate:");
double salesTaxRate;
keyboard.nextDouble();
salesTaxRate = salesTaxRate/100; //same thing here
//now output
System.out.println("Item to be sold: " + item);
System.out.println("Original price of the item: " + originalPrice);
System.out.println("Price after mark up: " + (originalPrice + originalPrice * markedUpPrice));
//similarly, do for sales tax

Java Lemonade Calculator

Assignment is to:
Display any welcome message at the top of the output screen
Create variables to hold the values for the price of a cup of lemonade.
Display the price per glass.
Ask the user for their name, and store it as a String object. Refer to the user by name, whenever you can.
Ask the user how many glasses of lemonade they would like to order. Save this as a variable with the appropriate data type.
Store the San Diego tax rate of 8% as a constant variable in your program.
Calculate the subtotal, total tax, and total price, and display it on the screen.
Ask the user how they would like to pay for the lemonade, and save the input as a char variable.
Ask the user to enter either 'm' for money, 'c' for credit card, or 'g' for gold
Using the DecimalFormat class, make all currency data printed to the screen display 2 decimal places, and also a '$" sign.
Need help figuring out how to get tax rate of 8% as a constant variable in my program
that way I can calculate the subtotal, total tax, and total price, and display it on the screen
So far this is what I have:
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
public class FirstProgram {
public static void main(String[] args) {
double cost = 7.55;
double amount = 7.55;
final double CA_SALES_TAX = 0.08;
int tax, subtotal, total;
subtotal = (int) (amount * cost);
tax = (int) (subtotal * CA_SALES_TAX);
total = tax + subtotal;
Scanner input = new Scanner(System.in);
double fnum = 7.55, tax1 = fnum * 0.08, answer = tax1 + fnum;
System.out.println("Welcome to the best Lemonade you'll ever taste! ");
System.out.println("My lemonade would only cost you a measly: $" + amount);
System.out.println("What is your name?");
String first_name;
first_name = input.nextLine();
System.out.println("Hi " +first_name+ ", how many glasses of lemonade would you like?");
fnum = input.nextDouble();
System.out.println("Subtotal: $" + (amount * fnum));
System.out.println("Tax: $" + (tax1 * CA_SALES_TAX));
tax1 = input.nextDouble();
Any help is appreciated
It looks like you already have the sales tax set as constant that is what the "final" keyword is being used for. As for your code i see some redundancies and am not sure as to why you are casting to integers. I made some mods for what I think you want it to do.
public static void main(String[] args) {
double cost = 7.55;
final double CA_SALES_TAX = 0.08;
double subtotal,tax,total;
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the best Lemonade you'll ever taste! ");
System.out.println("My lemonade would only cost you a measly: $" + cost);
System.out.println("What is your name?");
String first_name = input.nextLine();
System.out.println("Hi " +first_name+ ", how many glasses of lemonade would you like?");
int fnum = input.nextInt();
//calc subtotal, tax, total
subtotal = fnum * cost;
tax = subtotal *CA_SALES_TAX;
total = tax + subtotal;
// print them all out
System.out.println("Subtotal: $" + (subtotal));
System.out.println("Tax: $" + (tax));
System.out.println("Total Price: $" + (total));
}

error when reading data, manipulating it, and outputting it

Having problems in my while loop. I'm getting a
Exception in thread "main" java.util.NoSuchElementException: No line found.
at java.util.Scanner.nextLine(Scanner.java:1516)
at Payroll.main(Payroll.java:70)`
Here's the code:
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
import java.io.*;
import java.util.Scanner;
public class Payroll
{
public static void main(String[] args) throws IOException //throws exceptions
{
//Declare variables
String fileInput; // To hold file input
String fileOutput; // To hold file output
String date; // To hold the date
String userInput; // To hold user input from JOptionPane
String employeeID = ""; // To hold employee ID
String employeeName = ""; // To hold employee name
double hours = 0.0; // To hold employee hours
double wageRate = 0.0; // To hold employee wage rate
double taxRate = 0.0; // To hold employee tax rate
double taxWithheld; // To hold employee taxes withheld
double grossPay; // To hold employee gross pay
double netPay; // To hold employee net pay
double totalGross = 0.0; // To hold total gross pay
double totalTax = 0.0; // To hold total tax withheld
double totalNet = 0.0; // To hold total net pay
DecimalFormat money = new DecimalFormat("#,##0.00");// used to format money later on
date = JOptionPane.showInputDialog("Enter pay period ending date (mm/dd/yyyy): "); //hold user input into date
//Open the input file
File file = new File("EmployeeList.txt");
if (!file.exists())// check to see if the file exists
{
JOptionPane.showMessageDialog(null, "The file EmployeeList.txt is not found.");
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("PastPayrolls.txt", true);
PrintWriter outputFile = new PrintWriter(fwriter);
outputFile.println("PAY PERIOD ENDING DATE: " + date);
while (inputFile.hasNext())
{
employeeID = inputFile.nextLine(); // Read info from first line and store it in employeeID
employeeName = inputFile.nextLine(); // Read info from next line and store it in employeeName
userInput = JOptionPane.showInputDialog("Employee Name: " +
employeeName +
"\nEnter number of" + // display employee name and ask for number of hours worked
" hours worked:");
hours = Double.parseDouble(userInput); // Store user's parsed input into hours
wageRate = inputFile.nextDouble(); // Read info from next line and store it in wageRate
taxRate = inputFile.nextDouble(); // Read info from next line and store it in taxRate
inputFile.nextLine(); // Read blank line
Paycheck paycheck = new Paycheck(employeeID, employeeName, wageRate, taxRate, hours);
paycheck.calcWages();
outputFile.println("Employee ID: " + paycheck.getEmployeeID());
outputFile.println("Name: " + paycheck.getEmployeeName());
outputFile.println("Hours Worked: " + hours);
outputFile.println("Wage Rate: $" + money.format(paycheck.getWageRate()));
outputFile.println("Gross Pay: $" + money.format(paycheck.getGrossPay()));
outputFile.println("Tax Rate: " + paycheck.getTaxRate());
outputFile.println("Tax Withheld: $" + money.format(paycheck.getTaxWithheld()));
outputFile.println("Net Pay: $" + money.format(paycheck.getNetPay()));
JOptionPane.showMessageDialog(null, "Employee ID: " + paycheck.getEmployeeID() +
"\nName: " + paycheck.getEmployeeName() +
"\nHours Worked: " + hours +
"\nWage Rate: $" + money.format(paycheck.getWageRate()) +
"\nGross Pay: $" + money.format(paycheck.getGrossPay()) +
"\nTax Rate: " + paycheck.getTaxRate() +
"\nTax Withheld: $" + money.format(paycheck.getTaxWithheld()) +
"\nNet Pay: $" + money.format(paycheck.getNetPay()));
totalGross += paycheck.getGrossPay();
totalTax += paycheck.getTaxWithheld();
totalNet += paycheck.getNetPay();
inputFile.nextLine();
}
}// end while loop
JOptionPane.showMessageDialog(null, "Total Pay Period Gross Payroll: $" + money.format(totalGross) +
"Total Pay Period Period Tax Withheld: $" + money.format(totalTax)+
"Total Pay Period Net Payroll: $" + money.format(totalNet));
outputFile.println();
outputFile.println("TOTAL PAY PERIOD GROSS PAYROLL: $" + money.format(totalGross));
outputFile.println("TOTAL PAY PERIOD TAX WITHHELD: $" + money.format(totalTax));
outputFile.println("TOTAL PAY PERIOD NET PAYROLL: $" + money.format(totalNet));
inputFile.close();
outputFile.close();
}
}'
Here is the other code containing my paycheck class:
`public class Paycheck
{
//Declare variables
private final String EMPLOYEE_ID; // Employee ID
private final String EMPLOYEE_NAME; // Employee Name
private final double WAGE_RATE; // Wage Rate
private final double TAX_RATE; // Tax Rate
private final double HOURS_WORKED; // Hours Worked
private double grossPay; // Gross Pay
private double taxWithheld; // Tax Withheld
private double netPay; // Net Pay
// Constructor
Paycheck(String id, String name, double wage, double tax, double hours)
{
EMPLOYEE_ID = id;
EMPLOYEE_NAME = name;
WAGE_RATE = wage;
TAX_RATE = tax;
HOURS_WORKED = hours;
}
public void calcWages()//calculates wages
{
grossPay = HOURS_WORKED * WAGE_RATE;
taxWithheld = grossPay * TAX_RATE;
netPay = grossPay - taxWithheld;
}//end calcWages
public String getEmployeeID()//returns Employee's ID
{
return EMPLOYEE_ID;
}//end getEmployeeID
public String getEmployeeName()//returns Employee's name
{
return EMPLOYEE_NAME;
}//end getEmployeeName
public double getWageRate()//returns Employee's wage rate
{
return WAGE_RATE;
}//end getWageRate
public double getTaxRate()//returns Employee's tax rate
{
return TAX_RATE;
}//end getTaxRate
public double getHoursWorked()//returns Employee's hours worked
{
return HOURS_WORKED;
}//end getHoursWorked
public double getGrossPay()//returns Employee's gross pay
{
return grossPay;
}//end getGrossPay
public double getTaxWithheld()//returns Employee's tax withheld
{
return taxWithheld;
}//end getTaxWithheld
public double getNetPay()//returns Employee's net pay
{
return netPay;
}//end getNetPay
}`
Sorry for the lengthy code. I figured someone might need a good majority of the code to figure out what was going wrong. If there are better ways of doing things as far as using better methods, I am forced to stick to simplicity, so please try and work within the realms of this code. I am a beginner in Java btw.
Thanks!
I'm guessing it's because you have:
while (inputFile.hasNext())
Use Scanner.hasNextLine.
Edit:
I tested your code with your sample input. I see what you mean now.
while ( inputFile.hasNextLine() ) {
employeeID = inputFile.nextLine(); // Read info from first line and store it in employeeID
employeeName = inputFile.nextLine(); // Read info from next line and store it in employeeName
userInput = JOptionPane.showInputDialog( "Employee Name: " + employeeName + "\nEnter number of" + // display employee name and ask for number of hours worked
" hours worked:" );
hours = Double.parseDouble( userInput ); // Store user's parsed input into hours
wageRate = inputFile.nextDouble(); // Read info from next line and store it in wageRate
taxRate = inputFile.nextDouble(); // Read info from next line and store it in taxRate
Using hasNextLine as your condition will only ensure that the next call to nextLine will be valid. But, your calling nextLine twice, and then calling nextDouble after that. You can either (1) ensure that the calls your making match up with the file exactly, or (2) check that there is a next token every time you call next. I think (1) is your problem.
I was able to fix your program with the following:
while ( inputFile.hasNextLine() ) {
employeeID = inputFile.nextLine();
employeeName = inputFile.nextLine();
userInput = JOptionPane.showInputDialog( "Employee Name: " + employeeName + "\nEnter number of hours worked:" );
hours = Double.parseDouble( userInput );
wageRate = Double.parseDouble(inputFile.nextLine());
taxRate = Double.parseDouble(inputFile.nextLine());
Paycheck paycheck = new Paycheck( employeeID, employeeName, wageRate, taxRate, hours );
paycheck.calcWages();
JOptionPane.showMessageDialog( null, "Employee ID: " +
paycheck.getEmployeeID() + "\nName: " +
paycheck.getEmployeeName() + "\nHours Worked: " +
hours + "\nWage Rate: $" +
money.format( paycheck.getWageRate() ) + "\nGross Pay: $" +
money.format( paycheck.getGrossPay() ) + "\nTax Rate: " +
paycheck.getTaxRate() + "\nTax Withheld: $" +
money.format( paycheck.getTaxWithheld() ) + "\nNet Pay: $" +
money.format( paycheck.getNetPay() ) );
}
The file contents:
00135
John Doe
10.50
0.20
00179
Mary Brown
12.50
1.20

Categories

Resources