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
Related
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
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
I'm a junior in high school. Having a tough time figuring out how to use money format. I'm doing an exercise in A Guide to Programming in Java (Second Edition) where I have to prompt the employees for the number of burgers, fries, and sodas.
Fries are $1.09, burgers are $1.69, and sodas are $0.99.
Here is my code:
import java.util.Scanner;
/**
* Order pg. 101
*
* Garret Mantz
* 2/10/2016
*/
public class Order {
public static void main(String[]args) {
final double pburgers=1.69;
final double pfries=1.09;
final double psodas=0.99;
final double ptax=0.065;
double burgers;
double fries;
double sodas;
double totaltax;
double total;
double tax;
double tendered;
double change;
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount of burgers: ");
burgers = input.nextDouble();
System.out.print("Enter the amount of fries: ");
fries = input.nextDouble();
System.out.print("Enter the amount of sodas: ");
sodas = input.nextDouble();
System.out.print("Enter the amount tendered: ");
tendered = input.nextDouble();
totaltax = (burgers*pburgers)+(fries*pfries)+(sodas*psodas);
tax = totaltax*ptax;
total = totaltax + tax;
change = tendered - total;
System.out.println("Your total before tax is: \n" + totaltax);
System.out.println("Tax: \n" + tax);
System.out.println("Your final total is: \n" + total);
System.out.println("Your change is: \n" + change);
}
}
I just want to use the money format, but I'm not sure how. I'm sure it's a dumb question, but thank you for helping out!
Change your println to these, and see if that helps:
System.out.format("Your total before tax is: $%-5.2f\n", totaltax);
System.out.format("Tax: $%-5.2f\n", tax);
System.out.format("Your final total is: $%-5.2f\n", total);
System.out.format("Your change is: $%-5.2f\n", change);
There is also this:
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String totalTaxString = formatter.format(totaltax);
String taxString = formatter.format(tax);
String totalString = formatter.format(total);
String changeString = formatter.format(change);
System.out.format("Your total before tax is: %s\n", totalTaxString);
System.out.format("Tax: %s\n", taxString);
System.out.format("Your final total is: %s\n", totalString);
System.out.format("Your change is: %s\n", changeString);
Output:
Your total before tax is: $8.53
Tax: $0.55
Your final total is: $9.08
Your change is: $10.92
I'm trying to make it so each transaction is time stamped, but I'm having an issue with the date object. I keep running into a syntax error every time the program gets to the constructor. Any ideas?
Thank you so much!!!
UPDATE: I changed it so the constructor class now says:
DateFormat df = new SimpleDateFormat("MM/dd/yy HH:mm");
Date dateobj = new Date();
But now I run into a null pointer expression as soon as it's called in the MainMenu method. How do I get it to work in all the methods like the array list?
/**
* Bank Account
*
* #author: Seth Killian
* #version: 1.
* #citations: All okay. Adapted online tutorials in using the scanner tools to create a menu and list array.
*/
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;
//import java.util.Calendar;
public class BankAccount
{
private double minbalance; // Minimum allowable account balance
private double maxdeposit; // Maximum allowable deposit
private double balance; // Account balance
private double rate; // Rate of annual interest in value of percent
private String AcctName; // Account name
private ArrayList<String> transactions;
public Date dateobj;
public DateFormat df;
/**
* Constructor for Bank Account Class with Starting Balance
* #param: Starting Balance
* #return: None
*/
public BankAccount(double startBalance)
{
DateFormat df = new SimpleDateFormat("MM/dd/yy HH:mm");
Date dateobj = new Date();
transactions = new ArrayList<String>();
balance = startBalance;
transactions.add("+ $" + startBalance + " Initial Balance " + df.format(dateobj) + " Bal: $" + balance);
minbalance = 0.25;
maxdeposit = 5000.00;
rate = 6; // Six percent annual interest
AcctName = "Seth Killian";
}
/**
* Main Menu which allows the user to select from options
* #param: None
* #return: None
*/
public void MainMenu()
{
Scanner in = new Scanner (System.in);
switch (in.nextInt())
{
case 0:
Initialize();
case 1:
System.out.println("Balance: $" + balance + " as of " + df.format(dateobj));
SelectOption();
case 2: //Make a deposit
double amount;
System.out.print("Deposit Amount: $");
amount = in.nextDouble();
if (!(amount > 0) || (amount > maxdeposit))
{transactions.add("* Attempted Deposit: $" + amount + " " + df.format(dateobj));}
if (!(amount > 0))
{System.out.println("Error: Amount must be greater than zero");}
else if (amount > maxdeposit)
{System.out.println("Error: Maximum Deposit $" + maxdeposit + ".");}
else
{
balance += amount;
transactions.add("+ $" + amount + " Deposit " + df.format(dateobj) + " Bal: $" + balance);
System.out.println("Success: Deposited $" + amount + " Balance: $" + balance);
}
SelectOption();
case 3: //Make a withdrawl
System.out.print("Withdrawl Amount: $");
amount = in.nextDouble();
if (!(amount > 0) || (amount > balance) || (balance-amount < minbalance))
{transactions.add("* Attempted Withdrawl: $" + amount + " " + df.format(dateobj));}
if (!(amount > 0))
{System.out.println("Error: Amount must be greater than zero");}
else if (amount > balance)
{System.out.println("Error: Insufficent Funds");}
else if (balance-amount < minbalance)
{System.out.println("Error: Minimum Balance $" + minbalance + ".");}
else
{
balance -= amount;
transactions.add("- $" + amount + " Withdrawl " + df.format(dateobj) + " Bal: $" + balance);
System.out.println("Success: Withdrew $" + amount + " Balance: $" + balance);
}
SelectOption();
case 4: //Apply Annual Interest
balance = balance + (balance * (rate/100.0));
transactions.add("Interest ("+ rate + "%) "+ df.format(dateobj) + " Bal: $" + balance);
System.out.println("Success: " + rate + "% Interest rate applied. Balance: $" + balance);
SelectOption();
case 5: // Print Log
System.out.println();
System.out.println("Transaction Log for " + AcctName);
System.out.println("---------------------------------------- ");
for(int x = 0; x < transactions.size(); x++)
{System.out.println(transactions.get(x));}
System.out.println("---------------------------------------- ");
SelectOption();
case 6: // Exits application
System.exit(0);
default: // Unrecognized Selection
System.out.println ("Error: Selection Unrecognized");
SelectOption();
}
}
/**
* Sets the Main Menu up
* #param: None
* #return: None
*/
public void Initialize()
{
System.out.print('\u000C'); // Clears the terminal screen
System.out.println("Welcome " + AcctName + "!");
System.out.println("======================================== ");
System.out.println("1) Check Balance\n2) Make a Deposit\n3) Make a Withdrawl\n4) Add Annual Interest\n5) Transaction Logs");
System.out.println("\n0) Clear Screen\n6) Exit Application");
System.out.println("======================================== ");
SelectOption();
}
/**
* Allows the user to make a selection.
* #param: None
* #return: None
*/
public void SelectOption()
{
System.out.print ("Selection: ");
MainMenu();
}
}
From Class SimpleDateFormat
Any characters in the pattern that are not in the ranges of ['a'..'z'] and ['A'..'Z'] will be treated as quoted text. For instance, characters like ':', '.', ' ', '#' and '#' will appear in the resulting time text even they are not embraced within single quotes.
A pattern containing any invalid pattern letter will result in a thrown exception during formatting or parsing.
Thus your line of code df = new SimpleDateFormat("MM/dd/yy HH:mm"); will throw an exception because of the /. Try putting the / in single quotes.
df = new SimpleDateFormat("MM'/'dd'/'yy HH:mm");
Also like #DavidColer's answer states, you never initialize your Date object.
Update
After testing it turns out that df = new SimpleDateFormat("MM/dd/yy HH:mm"); will work without the single quotes. I should have taken a look at Oracle's documentation here.
You need to either create an instance of your BankAccount class by passing a double, like so BankAccount ba = new BankAccount(100.0); or add a default constructor in your class. Like the following.
public BankAccount() {
this(0.25);
}
You never fully initialize the date.
DateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yy HH:mm");
Date date = new Date();
System.out.println(simpleDateFormat.format(date));
I do not see anywhere where you use your overloaded constructor or even instantiate an instance of your bankaccount class where is it in the code? if you are not using the overloaded constructor you should create a default constructor to instantiate your varibales.
public class BankAccount
{
final private double MINBALANCE; // Minimum allowable account balance
final private double MAXDEPOSIT; // Maximum allowable deposit
private double balance; // Account balance
private double rate; // Rate of annual interest in value of percent
private String AcctName; // Account name
private ArrayList<String> transactions;
public Date dateobj;
public DateFormat df;
public BankAccount()
{
MINBALANCE = 25.00; // Minimum allowable account balance this should be all caps for a constant
MAXDEPOSIT = 5000.00; // Maximum allowable deposit should also be a constant
balance = 0.0;
rate = 0.0;
AcctName = null;
transactions = new ArrayList<String>(10);
dateobj = new Date();
df = new SimpleDateFormat("MM/dd/yy HH:mm");
}
;
like so
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.