Java Output Malfunction - java

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

Related

How to fix program and NOT receive "Command Execution Failed" error message in Java?

This is my first class and first time using Java. I also need to display 'Employee Name, Rate of Pay, Hours Worked, Overtime Worked, Gross Pay, Total amount of deductions, & Net Pay in the program as well.
package calculatepayprogram;
import java.util.Scanner;
/**
* Calculate Pay Program
* CPT 307: Data Structures & Algorithms
* 7/5/2022
*/
public class CalculatePayProgram{
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
double RateOfPay;
int HoursWorked;
double GrossPay;
double OvertimeHours;
double OvertimePay;
double NetPay;
double TotalDeductions;
String name;
System.out.println("Enter Your Name: ");
name = reader.nextLine();
System.out.print("Enter Your Pay Per Hour: ");
RateOfPay = reader.nextDouble();
System.out.print("Enter Your Hours Worked: ");
HoursWorked = reader.nextInt();
System.out.print("Enter Your Overtime Hours Worked: ");
OvertimeHours = reader.nextDouble();
GrossPay = RateOfPay * HoursWorked;
OvertimePay = OvertimeHours * 1.5 * RateOfPay;
double Pay = OvertimePay + GrossPay;
System.out.println("Your Gross Pay For This Week Will Be $" + Pay);
double FederalTax = .15 * Pay;
double StateTax = .0307 * Pay;
double Medicare = .0145 * Pay;
double SocialSecurity = .062 * Pay;
double Unemployment = .0007 * Pay;
double TotalDeduct = FederalTax + StateTax + Medicare + SocialSecurity + Unemployment;
System.out.println("Your Total Deductions For This Week Will Be $" + TotalDeduct);
NetPay = Pay - TotalDeduct;
System.out.println("Your Net Pay For This Week Will Be $" + NetPay);
}
}

How to fix return values not show up on one of my method

I tried to return values from two of my 4 methods so I can use print out on my final methods. The return value doesn't show up and my results were null and 0.0.
import java.util.*;
public class payroll {
static Scanner console = new Scanner(System.in);
static double hour;
static String employee;
static double rate;
static double gross_pay;
static double tax;
static double deduction;
static double net_pay;
public static void main(String[] args) {
name();
number(hour, rate, tax, gross_pay, deduction, net_pay);
print();
}
public static String name() {
System.out.print("Please enter employee's name: ");
String employee = console.nextLine();
return employee;
}
public static double[] number(double hour, double rate, double tax, double gross_pay, double deduction, double net_pay) {
double[] pay = new double[7];
pay[1] = hour;
pay[2] = rate;
pay[3] = tax;
pay[4] = gross_pay;
pay[5] = deduction;
pay[6] = net_pay;
System.out.print("Please enter number of hours worked: ");
pay[1] = console.nextDouble();
System.out.print("Please enter rate of pay: ");
pay[2] = console.nextDouble();
System.out.print("Please enter federal tax rate: ");
pay[3] = console.nextDouble();
pay[4]= hour*rate;
pay[5] = gross_pay*tax;
pay[6] = gross_pay-deduction;
return pay;
}
public static void print() {
System.out.printf("Employee's Name: " + employee + "\n" +
"Hours Worked: " + hour + "\n" +
"Hourly Pay: " + rate + "\n" +
"Gross Pay: " + gross_pay + "\n" +
"Tax Deducted: " + deduction + "\n" +
"Net Pay: " + net_pay);
}
}
The expected results are the name of the employee and the calculations made in the methods.
The issue here is that you are not assigning the return value to anything.
Normally you would do something like
employee = name();
But other points to mention is that you have employee etc declared as fields, so they are directly accessible via the methods
e.g.
public static void name() { // do not return any thing
System.out.print("Please enter employee's name: ");
// do not de-declare, just use the field
employee = console.nextLine();
}
This would be correct to use, as you are not passing any parameters to print and are printing out the values of the fields

NetBeans : Trying to create a class file to work with another program

Having trouble compiling these two files to run together.
I get a "can't find or load main class" error or a "erroneous tree" error.
Never asked for help on here before, hope this works :)
package savingsaccount;
import java.util.Scanner;
public class SavingsAccount
{
public static void main(String[] args)
{
double begginingBalance, deposit, withdraw;
int months;
double monthlyRate;
double plus = 0.0;
double minus = 0.0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the balance at beggining of " +
"accounting period.");
begginingBalance = keyboard.nextDouble();
System.out.println("Please enter number of months in current " +
"accounting period.");
months = keyboard.nextInt();
System.out.println("Enter the annual interest rate.");
monthlyRate = keyboard.nextDouble();
a7main accounting = new a7main();
for(int month = 1; month<=months; month++)
{
System.out.println("Enter the amount of deposits for month " +
month + " : ");
plus = keyboard.nextDouble();
accounting.deposits(plus);
System.out.println("Enter the amount of withdrawals for" +
" month " + month + ": ");
minus = keyboard.nextDouble();
accounting.withdrawals(minus);
accounting.interest(monthlyRate);
}
System.out.println("The account balance is: " +
accounting.getBalance());
System.out.println("The total amount of deposits is:" + plus);
System.out.println("The total amount of withdrwals is: " + minus);
System.out.println("The earned interest is: " +
accounting.getRate());
}
}
HERE IS THE CLASS FILE
I am trying to use the methods in this file to calculate and hold the values from the other file.
public class a7main
{
private double totalBalance;
private double interestRate;
public a7main(double balance,double rate)
{
totalBalance = balance;
interestRate = rate;
}
public void deposits(double deposit)
{
totalBalance = totalBalance+deposit;
}
public void withdrawals(double withdraw)
{
totalBalance = totalBalance-withdraw;
}
public void interest(double rate)
{
interestRate = totalBalance*rate;
}
public double getBalance()
{
return totalBalance;
}
public double getRate()
{
return interestRate;
}
}
#Alex Goad -
Add package name in a7main class
You have created parameterized constructor and no default constructor.
a7main accounting = new a7main();
The above line will look for default constructor like
public a7main(){
}

UserInput Method keeps assigning a different value in java

this is my first question on the site. I am a fresh CS student needing some help with something that is probably really simple. The code as is will compile. When I enter in the values as the program asks, it stores the values wrong. It will store the right values for gross pay and savings rate but the IRA rate comes back as 100% even when entered at 6.9 and it seems it stores the IRA rate in saveAmount. Please halp me figure out what I am doing wrong here.
import java.text.DecimalFormat;
import java.util.*;
public class CollinDunn_1_05 {
static Scanner console = new Scanner(System.in);
static DecimalFormat formatCash = new DecimalFormat("#,###.00");
static double iraTotal = 0.0;
static double saveAmount = 0.0;
static double totalSave = 0.0;
static String line = "";
public static void main (String [] args) {
// Input variables
double grossPay = 0.0; // The gross pay from a users paycheck
double saveRate = 0.0; // This is the user entered savings rate
double iraRate= 0.0; // The IRA investment rate
String whichOne = ""; // A temp variable to pass a string type into UserInput
printInfo();
grossPay = userInput("gross pay");
saveRate = userInput("savings rate");
iraRate = userInput("IRA rate");
iraTotal = iraAmount(grossPay, iraRate);
saveAmount = savingsAmount(grossPay, saveRate);
outputResults(grossPay, saveRate, saveAmount, iraRate, iraTotal);
return;
} // End Main
public static void printInfo() {
System.out.println ("This program uses methods to calculate \n"
+ "savings amounts and IRA investment amounts \n"
+ "from user input consisiting of their gross pay, \n"
+ "their desired savings rate and IRA rate, made by "
+ " Collin Dunn");
return;
} // End ProgramInfo
public static double userInput(String whichOne) {
double saveMe = 0.0;
System.out.print("Please enter your " + whichOne + ": ");
saveMe = console.nextDouble();
return saveMe;
} // End userInput
public static double iraAmount(double grossPay, double iraRate) {
iraTotal = grossPay * (iraRate / 100.0);
return iraTotal;
} // End iraAmount
public static double savingsAmount(double grossPay, double saveRate) {
saveAmount = grossPay * (saveRate / 100.0);
return saveAmount;
} // End savingsAmount
public static void outputResults(double grossPay, double saveRate, double iraRate,
double saveAmount, double iraTotal) {
totalSave = saveAmount + iraTotal;
System.out.print ("With a gross pay of $" + formatCash.format(grossPay)
+ ", a savings rate of %" + formatCash.format(saveRate)
+ " and a IRA rate of %" +formatCash.format(iraRate)
+ ".\n Your savings amount will be $" + formatCash.format(saveAmount)
+ ", with a investment amount of $" + formatCash.format(iraTotal)
+ ".\n Which leaves you with a total savings of $" +
+ totalSave + ". Way to go for paying yourself!" );
return;
} // End outputResults
} //End Class
Your only issue is the order of arguments you pass to or have set on the outputResults() method.
Change the signature of the method to:
public static void outputResults(double grossPay, double saveRate, double saveAmount, double iraRate, double iraTotal) {
Which now matches how you call the method:
outputResults(grossPay, saveRate, saveAmount, iraRate, iraTotal);
Let me make a couple of additonal suggestions:
1) You are consistently naming arguments in your method signatures the same names as global variables, which makes it confusing which is which when accessing the variable in the method. Either avoid using the same names for the method input variables, or use something like this.amount = amount to make it more obvious of your intention.
2) Avoid static unless you have a valid reason to use it (which is pretty rare).
Instead, take advantage of Java's Object oriented nature and create an instance of your class in the main method and call methods on that instance. This will make your code more readable, reliable, and reusable.
3) In a method that returns type 'void', you don't need to add the empty return; statement.
To correct your issue and also demonstrate the points I listed, I have refactored your code and provided it below. By the way, you have a lot of potential. Despite the fact there are a few details you can improve, for being a first year CS student, your code is well written and thought out. Good job!
import java.text.DecimalFormat;
import java.util.*;
public class CollinDunn_1_05 {
DecimalFormat formatCash = new DecimalFormat("#,###.00");
double iraTotal = 0.0;
double saveAmount = 0.0;
double totalSave = 0.0;
double grossPay = 0.0; // The gross pay from a users paycheck
double saveRate = 0.0; // This is the user entered savings rate
double iraRate= 0.0; // The IRA investment rate
public CollinDunn_1_05(double gross, double saveRt, double iraRt){
this.grossPay = gross;
this.saveRate = saveRt;
this.iraRate = iraRt;
}
public void calculate(){
calcIraAmount();
calcSavingsAmount();
}
public static void main (String [] args) {
Scanner scanner = new Scanner(System.in);
printInfo();
CollinDunn_1_05 program = new CollinDunn_1_05(
userInput("gross pay", scanner),
userInput("savings rate", scanner),
userInput("IRA rate", scanner)
);
program.calculate();
program.outputResults();
} // End Main
public static void printInfo() {
System.out.println ("This program uses methods to calculate \n"
+ "savings amounts and IRA investment amounts \n"
+ "from user input consisiting of their gross pay, \n"
+ "their desired savings rate and IRA rate, made by "
+ " Collin Dunn");
return;
} // End ProgramInfo
public static double userInput(String whichOne, Scanner console) {
double saveMe = 0.0;
System.out.print("Please enter your " + whichOne + ": ");
saveMe = console.nextDouble();
return saveMe;
} // End userInput
public void calcIraAmount() {
iraTotal = grossPay * (iraRate / 100.0);
} // End iraAmount
public void calcSavingsAmount() {
saveAmount = grossPay * (saveRate / 100.0);
} // End savingsAmount
public void outputResults() {
totalSave = saveAmount + iraTotal;
System.out.print ("With a gross pay of \$" + formatCash.format(grossPay)
+ ", a savings rate of %" + formatCash.format(saveRate)
+ " and a IRA rate of %" +formatCash.format(iraRate)
+ ".\n Your savings amount will be \$" + formatCash.format(saveAmount)
+ ", with a investment amount of \$" + formatCash.format(iraTotal)
+ ".\n Which leaves you with a total savings of \$" +
+ totalSave + ". Way to go for paying yourself!" );
} // End outputResults
} //End Class

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