Java: Calculating Employee's Wage - java

I have again a problem regarding on how to display the calculated wage of the employee..
When I type in the hourly rate, the Gross Salary won't display..
Here's what I've done so far..
The WageCalcu.java
public class WageCalcu
{
private String employeeName;
private int hours;
private double rate, pay;
public void setEmployeeName ( String name )
{
employeeName = name;
}
public String getEmployeeName()
{
return employeeName;
}
public double calculatePay( int hours, double rate )
{
if ( hours > 40 )
{
int extraHours = hours - 40;
pay = ( 40 * rate ) + ( extraHours * rate );
}
else pay = hours * rate;
return pay;
}
public void displayEmployee()
{
System.out.printf( "Employee's name: %s", getEmployeeName() );
System.out.printf( "\nGross Salary: ", + pay );
}
}
The Employee.java
import java.util.Scanner;
public class Employee
{
public static void main(String[] args)
{
Scanner input = new Scanner( System.in);
WageCalcu employee = new WageCalcu();
System.out.print( "Enter Employee %s name: " );
String name = input.nextLine();
employee.setEmployeeName( name );
System.out.print( "Enter how many hours worked: " );
int hours = input.nextInt();
System.out.print( "Enter hourly rate: " );
double rate = input.nextInt();
employee.calculatePay( hours, rate );
employee.displayEmployee();
System.out.println();
}
}

I'm sure you meant:
System.out.printf( "\nGross Salary: %f", pay);
One more thing
double rate = input.nextInt();
Should be
double rate = input.nextDouble();
If you're really expecting a real number.

I would put: System.out.printf( "\nGross Salary: %.2f", pay); to show 2 decimals.

You have missed %s in printf( "\nGross Salary: ", + pay );

Five years late to this party, but I'll speak my piece.
You've set it up to determine how many overtime hours an employee has, but you're not calculating their overtime pay.
What you have:
pay = ( 40 * rate ) + ( extraHours * rate );
What it should be:
pay = ( 40 * rate ) + ( extraHours * rate * 1.5);

Related

Java Output Malfunction

I created a problem with the goal to produce a pay stub. This program will not generate any regular pay output, instead just saying "$0.00". Can't figure out the problem.
Expected: "Regular Hours: 40 Reg Rate: $15.50 Reg Pay:
$620.00 "
My code: "Regular Hours: 40 Reg Rate: $15.50 Reg
Pay: $0.00 "
I've attempted to reformat it but I am still getting this error.
public class Activity2PayStub {
public static final double OVERTIME_FACTOR = 1.5;
public static final double FEDERAL_FACTOR = 0.2;
public static final double SOCIAL_FACTOR = 0.1;
private String employeeName;
private String employeeSSN;
private int regularH;
private int overtimeH;
private double payrateH;
private double regularPay = (regularH * payrateH);
private double overtimePR = payrateH * (OVERTIME_FACTOR);
private double overtimePay = overtimePR * overtimeH;
private double grossPay = regularPay + overtimePay;
private double ssTax = grossPay * (SOCIAL_FACTOR);
private double federalTax = (grossPay - ssTax) * (FEDERAL_FACTOR);
private double netPay = grossPay - (federalTax + ssTax);
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Activity2PayStub a2ps = new Activity2PayStub();
a2ps.getInput(keyboard);
a2ps.calculate();
a2ps.printPayStub();
}
/** #param keyboard command-line arguments. */
public void getInput(Scanner keyboard) {
System.out.print("Enter employee name: ");
employeeName = keyboard.nextLine();
System.out.print("Enter employee SNN (incl. hyphens: ");
employeeSSN = keyboard.nextLine();
System.out.print("Enter number of regular hours worked: ");
regularH = keyboard.nextInt();
System.out.print("Enter number of overtime hours worked: ");
overtimeH = keyboard.nextInt();
System.out.print("Enter hourly pay rate : ");
payrateH = keyboard.nextDouble();
}
public void calculate() {
}
/** simply prints. */
public void printPayStub() {
Scanner input = new Scanner(System.in);
System.out.println("_______________________"
+ "_____________________________________________");
String format = "Name: %-37s SSN: %-11s\n";
System.out.printf(format, employeeName, employeeSSN);
format = "Regular Hours: %-8d Reg Rate: $%-8.2f Reg Pay: $%-8.2f\n";
System.out.printf(format, regularH, payrateH, regularPay);
format = "Overtime Hours: %-8dOT Rate: $%-8.2f OT Pay: $%-8.2f\n";
System.out.printf(format, overtimeH, overtimePR, overtimePay);
format = "Gross Pay: $%-8.2f\n";
System.out.printf(format, grossPay);
format = "SS Withholding: $%-8.2f\n";
System.out.printf(format, ssTax);
format = "Federal Tax: $%-8.2f\n";
System.out.printf(format, federalTax);
format = "Net Pay: $%-8.2f\n";
System.out.printf(format, netPay);
System.out.println("________________________"
+ "__________________________________________");
}
}
That is because the calculations are performed at instance creation. You should move the calculations to the calculate() method.
The JLS chapter 8.3.2 confirms this:
If the declarator is for an instance variable (that is, a field that is not static), then the variable initializer is evaluated and the assignment performed each time an instance of the class is created

How to store 2 variables and compare them

I am trying to accept user input for two people's hourly wage and the amount of hours of overtime they work per year.
using an algorithm I have researched, the program will tell both people the amount of money they make per year and the amount of taxes they pay, which is based on the amount that they make.
This is all fine and dandy. However, what I am now trying to do is to add a line at the end of the program which states who is paying more taxes. This would be accomplished with the method whoPaysMoreTaxes, but I have no idea what to include in that method. I know I would need a simple if/ else if/ else statement to get the job done, but I do not know how I would go about storing the taxes of person 1 and the taxes of person 2 and compare them. The output should be as follows I believe. The numbers 22, 100, 58, and 260 are user input:
Person 1's hourly wage: 22
Person 1's overtime hours for the year: 100
You will make $45540 this year
And you will pay $9108 in taxes
Person 2's hourly wage: 58
Person 2's overtime hours for the year: 260
You will make $133980 this year
And you will pay $40194 in taxes.
Person 2 is paying more taxes.
The issue I am having is finding a way to produce that final line that says who is paying more taxes.
public class conditionalsAndReturn
{
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
taxes(console, 1);
taxes(console, 2);
}
public static void taxes(Scanner console, int personNum)
{
System.out.print("Person " + personNum + "'s hourly wage: ");
int wage = console.nextInt();
System.out.print("Person " + personNum + "'s overtime hours for the year: ");
double totalOvertimeHours = console.nextInt();
int salary = annualSalary(wage, totalOvertimeHours);
System.out.println("You will make $" + salary + " this year");
System.out.println("And you will pay $" + taxation(salary) + " in taxes");
System.out.println();
}
public static int annualSalary(int wage, double totalOvertimeHours)
{
double workHoursPerWeek = 40 + totalOvertimeHours / 48;
return (int)(weeklyPay(wage, workHoursPerWeek) * 48);
}
public static double weeklyPay(int wage, double workHoursPerWeek)
{
if (workHoursPerWeek > 40)
{
return (wage * 40) + ((wage + wage / 2.0) * (workHoursPerWeek - 40));
}
else
{
return wage * workHoursPerWeek;
}
}
public static int taxation(int salary)
{
if (salary < 20000)
{
return 0;
}
else if (salary > 100000)
{
return salary * 3 / 10;
}
else
{
return salary * 2 / 10;
}
}
public static String whoPaysMoreTaxes(
}
The OOP conform coding would be, to have a class person (or better employee), with the fields: personNum, one or more of the three wage/salary variables, taxation. Add name and such if needed.
Now you can use instances of those class to store the accumulated data, and compare the objects with a compareTo.
If you were to follow true Object Oriented programming principles, then you might create a separate class which represents a Person object (or consider a nested class). Then each Person instance could have the attributes:
hourly_wage
overtime_hours
income
taxes_owed
You would then want to create as many People classes as you need, using the class instances to store data. You could then modify your method header to be:
public Person who_payes_more_taxes(Person p1, Person p2): { ... }
Inside the method you would need to decide how to compare taxes, but most likely it will look something like:
if (p1.taxes_owed > p2.taxes_owed) { return p1 }
You're definitely on the right track. I would use more variables to simplify comparing the taxes:
import java.util.Scanner;
public class ConditionalsAndReturn
{
public static void main(String[] args)
{
int personOneWage;
int personOneOvertime;
double personOnePayBeforeTax;
double personOneTaxes;
double personOneNetIncome;
int personTwoWage;
int personTwoOvertime;
double personTwoPayBeforeTax;
double personTwoTaxes;
double personTwoNetIncome;
Scanner scan = new Scanner(System.in);
System.out.print("Person 1's hourly wage: ");
personOneWage = scan.nextInt();
System.out.print("Person 1's overtime hours for the year: ");
personOneOvertime = scan.nextInt();
personOnePayBeforeTax = (40 * personOneWage) + (personOneOvertime * personOneWage * 1.5);
personOneTaxes = taxes(personOnePayBeforeTax);
personOneNetIncome = personOnePayBeforeTax - personOneTaxes;
System.out.println("You will make $" + personOneNetIncome + " this year");
System.out.println("And you will pay $" + personOneTaxes + " in taxes");
System.out.print("Person 2's hourly wage: ");
personTwoWage = scan.nextInt();
System.out.print("Person 2's overtime hours for the year: ");
personTwoOvertime = scan.nextInt();
personTwoPayBeforeTax = (40 * personTwoWage) + (personTwoOvertime * personTwoWage * 1.5);
personTwoTaxes = taxes(personTwoPayBeforeTax);
personTwoNetIncome = personTwoPayBeforeTax - personTwoTaxes;
System.out.println("You will make $" + personTwoNetIncome + " this year");
System.out.println("And you will pay $" + personTwoTaxes + " in taxes");
if (personOneTaxes > personTwoTaxes)
{
System.out.println("Person 1 is paying more in taxes.");
}
else
{
System.out.println("Person 2 is paying more in taxes.");
}
scan.close();
}
private static double taxes(double payBeforeTax)
{
if (payBeforeTax < 20000)
{
return 0;
}
else if (payBeforeTax > 100000)
{
return payBeforeTax * 3 / 10;
}
else
{
return payBeforeTax * 2 / 10;
}
}
}

How can I ask a user if they want to modify information and then apply the change?

This is a basic Java practice question that I have seen, but I wanted to step it up a notch and include functionalities that ask the user whether or not they want to modify an employee's information and if so which one, then apply the requested modifications to the employee and display the updated employees information one more time.
Here is my code thus far:
public class Employee
{
private String firstName;
private String lastName;
private double monthlySalary;
private String decision;
// constructor to initialize first name, last name and monthly salary
public Employee( String first, String last, double salary )
{
firstName = first;
lastName = last;
if ( salary >= 0.0 ) // determine whether salary is positive
monthlySalary = salary;
} // end three-argument Employee constructor
// set Employee's first name
public void setFirstName( String first )
{
firstName = first;
} // end method setFirstName
// get Employee's first name
public String getFirstName()
{
return firstName;
} // end method getFirstName
// set Employee's last name
public void setLastName( String last )
{
lastName = last;
} // end method setLastName
// get Employee's last name
public String getLastName()
{
return lastName;
} // end method getLastName
// set Employee's monthly salary
public void setMonthlySalary( double salary )
{
if ( salary >= 0.0 ) // determine whether salary is positive
monthlySalary = salary;
} // end method setMonthlySalary
// get Employee's monthly salary
public double getMonthlySalary()
{
return monthlySalary;
} // end method getMonthlySalary
// set Employee's new monthly salary
public void setNewMonthlySalary( double salary )
{
monthlySalary = salary;
} // end method setMonthlySalary
// get Employee's new monthly salary
public double getNewMonthlySalary()
{
return monthlySalary;
} // end method getMonthlySalary
} // end class Employee
and the EmployeeTest class
import java.util.Scanner;
public class EmployeeTest
{
public static void main( String args[] )
{
Employee employee1 = new Employee( "Bo", "Jackson", 8875.00 );
Employee employee2 = new Employee( "Cam", "Newton", 13150.75 );
// create Scanner to obtain input from command window
Scanner input = new Scanner(System.in);
// display employees
System.out.printf( "Employee 1: %s %s; Yearly Salary: %.2f\n",
employee1.getFirstName(), employee1.getLastName(),
12 * employee1.getMonthlySalary() );
System.out.printf( "Employee 2: %s %s; Yearly Salary: %.2f\n",
employee2.getFirstName(), employee2.getLastName(),
12 * employee2.getMonthlySalary() );
// enter new employee salaries
System.out.println( "Enter " + employee1.getFirstName() + "'s new salary:" );
double newSalary1 = input.nextDouble();
employee1.setNewMonthlySalary( newSalary1 );
System.out.println( "Enter " + employee2.getFirstName() + "'s new salary:" );
double newSalary2 = input.nextDouble();
employee2.setNewMonthlySalary( newSalary2 );
// display employees with new yearly salary
System.out.printf( "Employee 1: %s %s; Yearly Salary: %.2f\n",
employee1.getFirstName(), employee1.getLastName(),
12 * newSalary1 );
System.out.printf( "Employee 2: %s %s; Yearly Salary: %.2f\n",
employee2.getFirstName(), employee2.getLastName(),
12 * newSalary2 );
} // end main
} // end class EmployeeTest
After displaying the employee information I would like to prompt the user to choose whether or not to make a change to an employee's salary. If so, then which employee. After the change is made I would like to display the the modified results. What would be the easiest way to handle this?
After some tweaking to my nested-ifs statements I figured out a way to achieve what I was looking for. I can't say that I was looking for answers to homework as I am no longer in school. I was simply looking for an easier way to achieve my goal by taking the path of least resistance...something that would have made coding easier and more concise. Although my answer is slightly bulkier than what I would have liked, it does still accomplish the task at hand. I will be working more to improve the application, but here is what I came up with:
import java.util.Scanner;
import javax.swing.JOptionPane;
import javax.swing.JDialog;
public class EmployeeTest
{
public static void main( String args[] )
{
// create Scanner to obtain input from command window
Scanner input = new Scanner(System.in);
Employee employee1 = new Employee( "Bo", "Jackson", 8875.00 );
Employee employee2 = new Employee( "Cam", "Newton", 13150.75 );
// display employees
System.out.printf( "Employee 1: %s %s; Yearly Salary: %.2f\n",
employee1.getFirstName(), employee1.getLastName(),
12 * employee1.getMonthlySalary() );
System.out.printf( "Employee 2: %s %s; Yearly Salary: %.2f\n",
employee2.getFirstName(), employee2.getLastName(),
12 * employee2.getMonthlySalary() );
JDialog.setDefaultLookAndFeelDecorated(true);
int response1 = JOptionPane.showConfirmDialog(null, "Do you wnat to change an employee's salary?",
"Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (response1 == JOptionPane.NO_OPTION)// if NO is clicked
{
System.out.println("See you next time");
} else if (response1 == JOptionPane.YES_OPTION)// if YES is clicked
{
// option to change the salary for employee 1
int response2 = JOptionPane.showConfirmDialog(null, "Would you like to change " + employee1.getFirstName() + " " + employee1.getLastName() + "'s salary:",
"Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (response2 == JOptionPane.NO_OPTION)// if NO is clicked
{
// option to change the salary for employee 2
int response3 = JOptionPane.showConfirmDialog(null, "Would you like to change " + employee2.getFirstName() + " " + employee2.getLastName() + "'s salary:",
"Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (response3 == JOptionPane.NO_OPTION)
{
System.out.println("See you next time");
} else if (response3 == JOptionPane.YES_OPTION)// if YES is clicked
{
// enter new salary for employee 2
System.out.println( "Enter " + employee2.getFirstName() + " " + employee2.getLastName() + "'s new salary:" );
double newSalary2 = input.nextDouble();
employee2.setNewMonthlySalary( newSalary2 );
// display unchanged salary for employee 1
System.out.printf( "Employee 1: %s %s; Yearly Salary: %.2f\n",
employee1.getFirstName(), employee1.getLastName(),
12 * employee1.getMonthlySalary() );
// display new yearly salary for employee 2
System.out.printf( "Employee 2: %s %s; Yearly Salary: %.2f\n",
employee2.getFirstName(), employee2.getLastName(),
12 * newSalary2 );
} else if (response3 == JOptionPane.CLOSED_OPTION)// if JOPTIONPANE is closed
{
System.out.println("JOptionPane closed");
}// END RESPONSE 3
} else if (response2 == JOptionPane.YES_OPTION)// if YES is clicked
{
// enter new salary for employee 1
System.out.println( "Enter " + employee1.getFirstName() + " " + employee1.getLastName() + "'s new salary:" );
double newSalary1 = input.nextDouble();
employee1.setNewMonthlySalary( newSalary1 );
// display new yearly salary for employee 1
System.out.printf( "Employee 1: %s %s; Yearly Salary: %.2f\n",
employee1.getFirstName(), employee1.getLastName(),
12 * newSalary1 );
// display unchanged salary for employee 2
System.out.printf( "Employee 2: %s %s; Yearly Salary: %.2f\n",
employee2.getFirstName(), employee2.getLastName(),
12 * employee2.getMonthlySalary() );
} else if (response2 == JOptionPane.CLOSED_OPTION)// if JOPTIONPANE is closed
{
System.out.println("JOptionPane closed");
}// END RESPONSE 2
{
}
} else if (response1 == JOptionPane.CLOSED_OPTION)// if JOPTIONPANE is clicked
{
System.out.println("JOptionPane closed");
}// END RESPONSE 1
} // end main
} // end class EmployeeTest
public class "Employee" did not change for post above.

For loop increments array backwards

I am trying to do some calculations using different values stored in an array. The problem is that my array's values increase but the calculations are coming out decreasing.
Main:
public static void main(String[] args) {
double pay, rate, deposit;
int years;
char yes = 'y';
char answer;
double[] interest = new double[15];
interest[0] = 3.75;
interest[1] = 4.00;
interest[2] = 4.25;
interest[3] = 4.50;
interest[4] = 4.75;
interest[5] = 5.00;
interest[6] = 5.25;
interest[7] = 5.50;
interest[8] = 5.75;
interest[9] = 6.00;
interest[10] = 6.25;
interest[11] = 6.50;
interest[12] = 6.75;
interest[13] = 7.00;
interest[14] = 7.25;
mortgageClass mortgagePayment = new mortgageClass();
Scanner keyboard = new Scanner(System.in);
System.out.print("Are you a first time buyer? ");
answer = keyboard.next().charAt(0);
if (answer == yes)
{
mortgagePayment.setRate(4.50);
}
else
{
mortgagePayment.setRate(interest[0]);
}
System.out.print("What is your mortage term? ");
years = keyboard.nextInt();
mortgagePayment.setTermYears(years);
System.out.print("What is your amount of mortgage? ");
pay = keyboard.nextDouble();
mortgagePayment.setAmount(pay);
System.out.print("What is your deposit amount? ");
deposit = keyboard.nextDouble();
mortgagePayment.setdepositAmt(deposit);
System.out.printf("Your mortgage payment is %.2f ", mortgagePayment.getMonthlyPayment());
System.out.println();
for ( int i = 0; i < interest.length; i++ ){
mortgagePayment.setRate(interest[i]);
System.out.printf("Your mortgage payment is %.2f ", mortgagePayment.getMonthlyPayment());
System.out.println();
}
}
MortgagePayment Class
public class mortgageClass {
private double rate;
private double loanAmount;
private double depositAmt;
private int termYears;
public void setRate(double r) {
rate = r;
}
public void setAmount(double loan) {
loanAmount = loan;
}
public void setTermYears(int years) {
termYears = years;
}
public void setdepositAmt(double amount) {
depositAmt = amount;
}
public double getMonthlyPayment() {
rate /= 100.0;
loanAmount = loanAmount - depositAmt;
double monthlyRate = rate / 12.0;
int termMonths = termYears * 12;
double monthlyPayment = (loanAmount * monthlyRate)
/ (1 - Math.pow(1 + monthlyRate, -termMonths));
return monthlyPayment;
}
}
The output is decreasing
Your mortgage payment is 1309.00
Your mortgage payment is 1220.49 //my output
Your mortgage payment is 1128.42
When it should be increasing
Your mortgage payment is 1309.00
Your mortgage payment is 1331.44 //Expected output
Your mortgage payment is 1354.10
Obviously the first value is assigned correctly, so why isn't the increment working?
EDIT: I have added a print statement to see if the correct values are being used and it seems like they are
for ( int i = 0; i < interest.length; i++ ){
mortgagePayment.setRate(interest[i]);
//System.out.printf("Your mortgage payment is %.2f ", mortgagePayment.getMonthlyPayment());
System.out.println(interest[i]);
System.out.printf("Your mortgage payment is %.2f ", mortgagePayment.getMonthlyPayment());
System.out.println();
Output:
3.75
Your mortgage payment is 1309.00
4.0
Your mortgage payment is 1220.49
4.25
Your mortgage payment is 1128.42
4.5
Your mortgage payment is 1032.74
..... I would just like to know WHY the calculations are decreasing.
skip
interest[i] = i + 1;
EDITED 2nd time :
the problem is
loanAmount = loanAmount - depositAmt;
every time you call mortgagePayment.getMonthlyPayment()
it decreasing the loanAmount , Thats why monthly amount is coming down
suggested change :
public double getloanAmount(){
return loanAmount - depositAmt;
}
public double getMonthlyPayment() {
rate /= 100.0;
double loanAmount = getloanAmount();
double monthlyRate = rate / 12.0;
int termMonths = termYears * 12;
double monthlyPayment = (loanAmount * monthlyRate) / (1 - Math.pow(1 + monthlyRate, -termMonths));
return monthlyPayment;
}
that will fix the problem.
EDITED :
use this fromula Monthly Mortgage Payment
M = P [ i(1 + i)^n ] / [ (1 + i)^n – 1]
The variables are as follows:
M = monthly mortgage payment
P = the principal, or the initial amount you borrowed.
i = your monthly interest rate. Your lender likely lists interest rates as an annual figure,
so you’ll have to divide by 12, for each month of the year. So, if your rate is 5%,
then the monthly rate will look like this: 0.05/12 = 0.004167.
n = the number of payments, or the payment period in months. If you take out a 30-year fixed rate mortgage,
this means: n = 30 years x 12 months per year = 360 payments.

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