Prompt for the program to end - java

I need to write a program for my CIS class, I feel I have the majority set up. Being 95%, To sum it all up simply. I have to write a program that prompts the user to input their name, pay rate, hours worked. It then takes the data, calculates the gross pay, then subtracts the tax, then prints it all to the screen. The program should allow multiple users to add data for however number of employee's, which forces me to believe I need to set a value they must enter to end the program. Problem is I am regrettably stumped on how to code it so when the value is entered, the program ends. I'm almost certain a while loop is needed, but any sort of feedback would be much appreciated.
package program1;
import java.util.*;
public class Program1 {
static Scanner console = new Scanner (System.in);
public static void main(String[] args) {
String firstName, lastName ;
double payRate;
int hoursWorked;
double netPay;
double grossPay;
String formatNet;
System.out.println("Please enter the employee's name. (Enter a -1 when finished): ") ;
firstName = console.nextLine();
lastName = console.nextLine();
System.out.println("Please enter the employee's pay rate. ");
payRate = console.nextDouble();
System.out.println("Please enter the employee's hours worked. ");
hoursWorked = console.nextInt();
if(hoursWorked > 40)
{
grossPay = payRate * hoursWorked * 1.5;
}
else
{
grossPay = payRate * hoursWorked;
}
netPay = grossPay - (grossPay * .15);
formatNet = String.format("%.2f", netPay);
System.out.println(firstName +" "+ lastName + "'s net pay is " + formatNet);
}
}

Yes, you need a loop. Try this code below.
Also note the presence of console.nextLine(); after
console.nextDouble(); and console.nextInt();.
public static void main(String[] args) {
String firstName, lastName;
double payRate;
int hoursWorked;
double netPay;
double grossPay;
String formatNet;
while (true){
System.out.println("Please enter the employee's name. (Enter a -1 when finished): ");
firstName = console.nextLine();
if ("-1".equals(firstName.trim())) break;
lastName = console.nextLine();
System.out.println("Please enter the employee's pay rate. ");
payRate = console.nextDouble();
console.nextLine();
System.out.println("Please enter the employee's hours worked. ");
hoursWorked = console.nextInt();
console.nextLine();
if (hoursWorked > 40) {
grossPay = payRate * hoursWorked * 1.5;
} else {
grossPay = payRate * hoursWorked;
}
netPay = grossPay - (grossPay * .15);
formatNet = String.format("%.2f", netPay);
System.out.println(firstName + " " + lastName + "'s net pay is " + formatNet);
}
}

Use do while loop and by using some condition you can terminate the loop like you can prompt user for "Do you want to continue(y/n)" and depending upon value you can iterate again.
EDIT
do
{
//your code goes here
System.out.println("Do you want to continue(y/n)?");
isContinue = console.next();
}while(isContinue = "Y" || isContinue = "y")
you can use break statement after checking firstname is -1 in if condition

Here is a solution. I threw in some Object-Orientation, method extraction and resource management to always close the Scanner after use.
import java.util.Scanner;
public class Program1 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
try {
do {
enterEmployee(console);
System.out.println("Another employee? (q to quit)");
} while (!"q".equals(console.nextLine()));
} finally {
console.close();
}
}
private static void enterEmployee(Scanner console) {
Employee employee = new Employee();
System.out.println("Please enter the employee's first name: ");
employee.setFirstName(console.nextLine());
System.out.println("Please enter the employee's last name: ");
employee.setLastName(console.nextLine());
System.out.println("Please enter the employee's pay rate: ");
employee.setPayRate(console.nextDouble());
console.nextLine();
System.out.println("Please enter the employee's hours worked: ");
employee.setHoursWorked(console.nextInt());
console.nextLine();
System.out.println(employee + "'s net pay is " + String.format("%.2f", employee.getNetPay()));
}
public static class Employee {
private String firstName;
private String lastName;
private double payRate;
private int hoursWorked;
private double netPay;
private double grossPay;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public double getPayRate() {
return payRate;
}
public void setPayRate(double payRate) {
this.payRate = payRate;
}
public int getHoursWorked() {
return hoursWorked;
}
public void setHoursWorked(int hoursWorked) {
this.hoursWorked = hoursWorked;
if (hoursWorked > 40) {
grossPay = payRate * hoursWorked * 1.5;
} else {
grossPay = payRate * hoursWorked;
}
netPay = grossPay - (grossPay * .15);
}
public double getNetPay() {
return netPay;
}
public double getGrossPay() {
return grossPay;
}
#Override
public String toString() {
return firstName + " " + lastName;
}
}
}

Related

I need my code to display the users name, their GPA, and then a credit which is their GPA times 10

I need my code to display the users name, their GPA, and then a credit which is their GPA times 10. The code below is what I have so far but every time I run the program the output is just, "EEEEEEEEEE EEEEEE....". Can you guys please tell me what I can do to fix this? All help is appreciated and thanks in advance!
import java.util.Scanner;
public class BookstoreCredit {
public static void main (String args[])
{
String name;
double gpa;
Scanner inputDevice = new Scanner(System.in);
System.out.print ("Please enter your name >>> ");
name = inputDevice.nextLine();
System.out.print ("Please enter your grade point average >>> ");
gpa = inputDevice.nextDouble();
System.out.print (name);
System.out.print (", your GPA is ");
System.out.print (gpa);
System.out.print (", so your credit is $");
}
public static void computeDiscount(String name, double gpa)
{
double credit;
credit = gpa * 10.0;
}
}
Are you talking something like this?:
import java.util.Scanner;
public class BookstoreCredit {
public static void main(String args[]) {
String name;
double gpa;
Scanner inputDevice = new Scanner(System.in);
System.out.print("Please enter your name >>> ");
name = inputDevice.nextLine();
System.out.print("Please enter your grade point average >>> ");
gpa = inputDevice.nextDouble();
System.out.print(name);
System.out.print(", your GPA is ");
System.out.print(gpa);
System.out.print(", so your credit is " + computeDiscount(gpa));
}
public static double computeDiscount(double gpa) {
double credit;
credit = gpa * 10.0;
return credit;
}
}

My program won't invoke my methods

I've only just begun programming, and I find most of my resources to be incredibly unhelpful. Hopefully you guys can help!
My program runs until it gets to the display methods, and then it just stops. No errors, and no build successful. It just continues with the user input. Any ideas?
Here is all of the program. I created a separate class for the object as well. Let me know if you think the problem could be there. Thanks!
import java.util.Scanner;
public class HernandezMortgageCalculator {
public static void main(String[] args) {
programDescription();
System.out.println();
MortgageLoan mortgageLoan1 = new MortgageLoan();
Scanner userInput = new Scanner(System.in);
System.out.println();
System.out.println("Please enter the home buyer's last name: ");
String lastName = userInput.nextLine();
System.out.println("Please enter the home's zip code: ");
String zipCode = userInput.nextLine();
System.out.println("Please enter the home value: ");
double homeValue = userInput.nextDouble();
System.out.println("Please enter the annual interest rate: ");
double annualInterestRate = userInput.nextDouble();
mortgageLoan1.setLoanIdentifier(mortgageLoan1.getLoanIdentifier());
mortgageLoan1.setHomeValue(userInput.nextDouble());
mortgageLoan1.setLoanAmount();
mortgageLoan1.setAnnualInterestRate(userInput.nextDouble());
System.out.println();
System.out.println();
displayLoanDetails(mortgageLoan1);
displayMortgageResults(mortgageLoan1);
}
public static void programDescription() {
System.out.println("This program implements a Mortgage Calulator");
System.out.println();
System.out.println("Given a home's purchase price and loan's annual" +
"interest rate, it will compute the monthly" +
"mortgage payment, which includes taxes, " +
"insurance principle and interest.");
}
public static void displayLoanDetails(MortgageLoan mortgageLoan1){
System.out.println();
System.out.println("Loan Details");
System.out.printf("  Loan identifier             %f "
+ mortgageLoan1.getLoanIdentifier());
System.out.println();
System.out.printf("  Loan amount                 %.2f "
+ mortgageLoan1.getLoanAmount() );
System.out.println();
System.out.printf("  Loan length                 %f "
+ mortgageLoan1.getLengthOfLoan() + " years");
System.out.println();
System.out.printf("  Annual Interest Rate        %.3f"
+ mortgageLoan1.getAnnualInterestRate() + "%");
System.out.println();
}
public static void displayMortgageResults (MortgageLoan mortgageLoan1) {
double monthlyPropertyTax = mortgageLoan1.calcMonthlyPropertyTax();
double monthlyInsurancePremium =
mortgageLoan1.calcMonthlyInsurancePremium();
double monthlyPrincipleAndLoan =
mortgageLoan1.calcMonthlyPrincipleAndLoan();
double totalMonthlyMortgage = monthlyPropertyTax + monthlyInsurancePremium
+ monthlyPrincipleAndLoan;
System.out.println();
System.out.println("Monthly Mortgage Payment");
System.out.printf("  Monthly Taxes                  %.2f",
monthlyPropertyTax);
System.out.println();
System.out.printf(" Monthly Insurance             %.2f",
monthlyInsurancePremium);
System.out.println();
System.out.printf("  Monthly Principle & Interest   %.2f",
monthlyPrincipleAndLoan);
System.out.println();
System.out.println("                               --------");
System.out.println();
System.out.printf("  Total Monthly Mortage Payment  %.2f",
totalMonthlyMortgage);
}
public class MortgageLoan {
private String loanIdentifier;
private double homeValue;
private double downPayment;
private double loanAmount;
private int lengthOfLoan;
private double annualInterestRate;
public MortgageLoan() {
loanIdentifier = "";
homeValue = 0.0;
downPayment = 10.0;
loanAmount = 0.0;
lengthOfLoan = 30;
annualInterestRate = 0.0;
}
public static char firstFour(String lastName){
char result = lastName.charAt(0);
result += lastName.charAt(1);
result += lastName.charAt(2);
result += lastName.charAt(3);
return result;
}
public static char firstThree(String zipCode){
char result = zipCode.charAt(0);
result += zipCode.charAt(1);
result += zipCode.charAt(2);
return result;
}
public static String lastNameZipCode(String lastName, String zipCode) {
String result = "";
result = lastName.toUpperCase();
result += firstFour(lastName);
result += firstThree(zipCode);
return result;
}
void setLoanIdentifier(String lastNameZipCode) {
loanIdentifier = lastNameZipCode;
}
void setHomeValue(double newHomeValue) {
homeValue = newHomeValue;
}
void setLoanAmount() {
double newLoanAmount = homeValue - homeValue * (downPayment/100);
loanAmount = newLoanAmount;
}
void setAnnualInterestRate(double newAnnualInterestRate) {
annualInterestRate = newAnnualInterestRate;
}
public String getLoanIdentifier() {
return loanIdentifier;
}
public double getLoanAmount(){
return loanAmount;
}
public int getLengthOfLoan(){
return lengthOfLoan;
}
public double getAnnualInterestRate(){
return annualInterestRate;
}
public double calcMonthlyPropertyTax() {
final double HOME_ASSED_VALUE_PERCENTAGE = 0.85;
final double ANNUAL_PROPERTY_TAXES_PERCENTAGE = 0.0063;
final double ADMIN_FEE = 35.00;
double homeAssessedValue = homeValue * HOME_ASSED_VALUE_PERCENTAGE;
double annualPropertyTaxes = (homeAssessedValue *
ANNUAL_PROPERTY_TAXES_PERCENTAGE + ADMIN_FEE);
double monthlyPropertyTax = annualPropertyTaxes/12;
return monthlyPropertyTax;
}
public double calcMonthlyInsurancePremium() {
final double ANNUAL_PREMIUM_PERCENTAGE = .0049;
double annualInsurancePremium = .0049 * homeValue;
double monthlyInsurancePremium = Math.round(annualInsurancePremium/12);
return monthlyInsurancePremium;
}
public double calcMonthlyPrincipleAndLoan(){
double monthlyInterestRate = annualInterestRate/100/12;
double Factor = Math.exp((lengthOfLoan*12) * Math.log
(monthlyInterestRate + 1));
double monthlyPrincipleAndLoan = (Factor * monthlyInterestRate *
loanAmount)/(Factor - 1);
return monthlyPrincipleAndLoan;
}
}

Correctly calling a method in a different class | Java

I got a superclass Employee and subclasses of that (HourlyEmployee and CommissionEmployee) and a tester class.
When I run the program and take in user values, after it asks for hours/sales and calculates pay - the value given is 0.0. The pay is not being calculated correctly - or at all - why is this and how can I do it correctly?
abstract class Employee {
// Data members
private String firstName;
private String lastName;
private int employeeNumber;
private int numberOfEmployees;
protected int hours;
protected int sales;
protected double pay;
// Default constructor
public Employee() {
firstName = null;
lastName = null;
employeeNumber = 0;
numberOfEmployees = 0;
}
// Getter and setter methods
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getEmployeeNumber() {
return employeeNumber;
}
public void setEmployeeNumber(int employeeNumber) {
this.employeeNumber = employeeNumber;
}
public int getNumberOfEmployees() {
return numberOfEmployees;
}
public void setNumberOfEmployees(int numberOfEmployees) {
this.numberOfEmployees = numberOfEmployees;
}
// Abstract method to be implemented in sublcasses
public abstract void earnings();
#Override
public String toString(){
return "First Name: " + getFirstName() + "\n" + "Last Name: " + getLastName() + "\n" +
"Employee Number: " + getEmployeeNumber() + "\n" + "Number of Employees: "
+ getNumberOfEmployees();
}
}
`
public class HourlyEmployee extends Employee {
// Constructor
public HourlyEmployee() {
//Calls default constructor in superclass
super();
}
// Establish the amount of pay for hourly employees
int rate = 15;
// Override earnings method
#Override
public void earnings(){
pay = hours * rate;
}
// Return String representation of class
public String toString(){
return "First Name: " + getFirstName() + "Last Name: " + getLastName() +
"Employee Number: " + getEmployeeNumber() + "Number of Employees: "
+ getNumberOfEmployees();
}
}
`
public class CommissionEmployee extends Employee {
// Constructor
public CommissionEmployee() {
//Calls default constructor in superclass
super();
}
// Establish the amount of pay for hourly employees
double commission = 0.10;
// Override earnings method
#Override
public void earnings(){
pay = commission * sales;
}
// Return String representation of class
public String toString(){
return "First Name: " + getFirstName() + "Last Name: " + getLastName() +
"Employee Number: " + getEmployeeNumber() + "Number of Employees: "
+ getNumberOfEmployees();
}
}
`
import java.util.LinkedList;
import java.util.Scanner;
public class EmployeeTester {
public static void main(String[] args) {
// Protected double only visible in superclass and subclass.
// Must be declared again in tester class.
double pay;
int hours;
int sales;
// Create new LinkedList
LinkedList<Employee> employeeList = new LinkedList<>();
// Create Scanner obkect
Scanner keyboard = new Scanner(System.in);
char yes = 'y';
int x = 0;
while(yes == 'y' || yes == 'Y'){
// Declare & create a HourlyEmployee odject
HourlyEmployee employee1 = new HourlyEmployee();
employeeList.add(employee1);
System.out.print("Enter First Name: ");
String firstName = keyboard.next();
employee1.setFirstName(firstName);
employeeList.get(x).setFirstName(firstName);
System.out.print("Enter Last Name: ");
String lastName = keyboard.next();
employee1.setLastName(lastName);
employeeList.get(x).setLastName(lastName);
System.out.print("Enter Employee Number: ");
int employeeNumber = keyboard.nextInt();
employee1.setEmployeeNumber(employeeNumber);
employeeList.get(x).setEmployeeNumber(employeeNumber);
System.out.print("Enter Number of Employees: ");
int numberOfEmployees = keyboard.nextInt();
employee1.setNumberOfEmployees(numberOfEmployees);
employeeList.get(x).setNumberOfEmployees(numberOfEmployees);
System.out.print("Enter Hours Worked: ");
hours = keyboard.nextInt();
// Calculate earnings
employee1.earnings();
System.out.println(employee1.toString());
System.out.println("Total Earnings: " + employee1.pay);
x++; // increment x
System.out.print("Continue? [y/n] ");
yes = keyboard.next().charAt(0);
}
// Declare & create a CommissionEmployee odject
CommissionEmployee employee2 = new CommissionEmployee();
employeeList.add(employee2);
System.out.print("Enter First Name: ");
String firstName = keyboard.next();
employee2.setFirstName(firstName);
employeeList.get(x).setFirstName(firstName);
System.out.print("Enter Last Name: ");
String lastName = keyboard.next();
employee2.setLastName(lastName);
employeeList.get(x).setLastName(lastName);
System.out.print("Enter Employee Number: ");
int employeeNumber = keyboard.nextInt();
employee2.setEmployeeNumber(employeeNumber);
employeeList.get(x).setEmployeeNumber(employeeNumber);
System.out.print("Enter Number of Employees: ");
int numberOfEmployees = keyboard.nextInt();
employee2.setNumberOfEmployees(numberOfEmployees);
employeeList.get(x).setNumberOfEmployees(numberOfEmployees);
System.out.print("Enter Sales Made: ");
sales = keyboard.nextInt();
// Calculate earnings
employee2.earnings();
System.out.println(employee2.toString());
System.out.println("Total Earnings: " + employee2.pay);
x++; // increment x
System.out.print("Continue? [y/n] ");
yes = keyboard.next().charAt(0);
}
}
You need to set hours and sales to the employee objects, currently, they are 0, because, as int, both sales and hours get initialized to 0,
So, commission * sales will become 0 and hours * rate will become 0.
In EmployeeTester, set Hours to the HourlyEmployee object
System.out.print("Enter Hours Worked: ");
hours = keyboard.nextInt();
employee1.setHours(hours);
In EmployeeTester, set Sales to the CommissionEmployee object
System.out.print("Enter Sales Made: ");
sales = keyboard.nextInt();
employee2.setSales(sales);
You need to add setHours method in Employee
public void setHours(int hours) {
this.hours = hours;
}
call this method in EmployeeTester after getting hours from that.

employee class will not calculate correctly

for the assignment, an employee has a ID number, hourly wage and works a certain # of hours. i need to calculate the gross income from those 2 values and then based of that there is withholding from the pay, in my code i believe all that is there but when i test my program i can only calculate the pay that was earned, the withholding and net pay come as a value of 0. i would appreciate any help on the issue, thank you.
// an employee has an ID, get paid an amout hourly and work an amount of hours
// tax is withheld depending on gross pay
public class Employee
{
//withholding calculation
public Employee(String empId, double hrsWrk, double hrPay)
{
employeeId = empId;
hoursWorked = hrsWrk;
hourlyPay = hrPay;
}
// access methods
public String getEmployeeId()
{
return employeeId;
}
public double getHoursWorked()
{
return hoursWorked;
}
public double getHourlyPay()
{
return hourlyPay;
}
public double getWithholding()
{
return withholding;
}
public double getIncome()
{
double income = hourlyPay * hoursWorked;
return income;
}
public double getNetPay()
{
double netPay = income - withholding;
return netPay;
}
// mutator methods
public void setId(String empId)
{
employeeId = empId;
}
public void setHoursWorked(double hrsWrk)
{
hoursWorked = hrsWrk;
}
public void setHourlyPay(double hrPay)
{
hourlyPay = hrPay;
}
//withholding calculator based on income
public void calcWithholding()
{
if(income <= 0)
{
withholding = 0.0;
}
else if(income >0 && income <= 300.0)
withholding = income*10.0/100;
else if(income >= 300.01 && income <= 400.0)
withholding = income*12/100;
else if(income >= 400.01 && income <= 500.0)
withholding = income*15/10;
else
withholding = income*20/100;
System.out.println("withholding is " + withholding);
}
public void displayWithholding()
{
calcWithholding();
System.out.println("Employee " + employeeId + " your income is " + getIncome() + " per week\n you have to pay " + getWithholding());
System.out.println("Employee " + employeeId + " your net income is " + getNetPay());
}
//instance fields
private String employeeId;
private double hoursWorked;
private double hourlyPay;
private double withholding;
private double income;
private double netPay;
}
here is the test program---------------------------------------------
import javax.swing.JOptionPane;
public class EmployeeTest
{
public static void main(String[] args)
{
String employeeId = JOptionPane.showInputDialog("Please enter your Employee ID");
String input = JOptionPane.showInputDialog("Enter your hourly wage");
double hourlyPay = Double.parseDouble(input);
input = JOptionPane.showInputDialog("How many hours have you worked this week?");
double hoursWorked = Double.parseDouble(input);
Employee richard = new Employee(employeeId, hoursWorked, hourlyPay);
richard.displayWithholding();
System.exit(0);
}
}
You're not calling getIncome until after calcWithHolding so the income variable is always zero during the calculation.
The current approach relies on side-effects from calling some of the accessors, this is generally considered to be a bad approach.
I would suggest one of the following
Ensure calculations done in the constructor (or called...)
Separate your concerns so that there is no confusion between data storage, object construction, data accessors and calculations.
Lazy initialization, so that calculated values are only calculated if they have never been accessed.

I am having trouble with the program skipping over the first input when looping. Please help

Ok, so I had to modify my already working program to use 2 separate classes...one to perform the task and one to store info. Once it does the first calculation and it gets to the second entry, it skips over employee name. Why? Please help. Here is the code:
package payroll_program_3;
import java.util.Scanner;
public class payroll_program_3
{
public static void main(String[] args)
{
Scanner input = new Scanner( System.in );
employee_info theEmployee = new employee_info();
String eName = "";
double Hours = 0.0;
double Rate = 0.0;
while(true)
{
System.out.print("\nEnter Employee's Name: ");
eName = input.nextLine();
theEmployee.setName(eName);
if (eName.equalsIgnoreCase("stop"))
{ return;
}
System.out.print("\nEnter Employee's Hours Worked: ");
Hours = input.nextDouble();
theEmployee.setHours(Hours);
while (Hours <0) { System.out.printf("Hours cannot be negative\n");
System.out.printf("Please enter hours worked\n");
Hours = input.nextDouble();
theEmployee.setHours(Hours);
}
System.out.print("\nEnter Employee's Rate of Pay: ");
Rate = input.nextDouble();
theEmployee.setRate(Rate);
while (Rate <0) { System.out.printf("Pay rate cannot be negative\n");
System.out.printf("Please enter hourly rate\n");
Rate = input.nextDouble();
theEmployee.setRate(Rate);
}
System.out.print("\n Employee Name: " + theEmployee.getName());
System.out.print("\n Employee Hours Worked: " + theEmployee.getHours());
System.out.print("\n Employee Rate of Pay: " + theEmployee.getRate() + "\n\n");
System.out.printf("\n %s's Gross Pay: $%.2f\n\n\n", theEmployee.getName(), theEmployee.calculatePay());
}
}
}
PART 2:
package payroll_program_3;
public class employee_info
{
String employeeName;
double employeeRate;
double employeeHours;
public employee_info()
{
employeeName = "";
employeeRate = 0;
employeeHours = 0;
}
public void setName(String name)
{
employeeName = name;
}
public void setRate(double rate)
{
employeeRate = rate;
}
public void setHours(double hours)
{
employeeHours = hours;
}
public String getName()
{
return employeeName;
}
public double getRate()
{
return employeeRate;
}
public double getHours()
{
return employeeHours;
}
public double calculatePay()
{
return (employeeRate * employeeHours);
}
}
There are two places where an infinite loop can occurring, as Hours & Rate are not changing inside of them.
while (Hours <0)
{
System.out.printf("Hours cannot be negative\n");
System.out.printf("Please enter hours worked\n");
}
while (Rate <0)
{
System.out.printf("Pay rate cannot be negative\n");
System.out.printf("Please enter hourly rate\n");
}
Haven't read all the code, but it is likely this needs to be an if statement containing a continue.
You need hours= input.next double to change hour var so it fails the while condition

Categories