Java Payroll Program, Totalling Payroll Hours and Total Pay Issues - java

For this program, I am trying to set up a payroll for inputted employees. The program has the user enter the employee's name, tax ID, and wage, and automatically generates an ID number for each employee entered. After this information is inputted, the user is asked to give the number of hours worked for 2 weeks. To do this, the employee ID number is entered to give reference to the employee that worked a certain number of hours. Next, either week 1 or 2 is entered to determine which week they worked. Finally, the number of hours worked that week is entered. Once the information is finished, the user enters 0 to stop entering the data, and the payroll is printed in a chart. The main issue I am having is that you MUST enter the ID, week, and hours for EACH employee added to the list, regardless of whether or not they worked in the 2 week period. I want to try and figure out how to set the Hours Worked and Total pay numbers to 0 if I do not enter any information for a certain employee. For example, if I enter: 1, for employee 1; 1, for week 1; 20, for hours worked in week 1; press enter; 1, again for employee 1; 2, for week 2; and 30, for hours worked in week 2, this information will print in the table. Say I have another employee, employee 2. I do not want to enter all of this information for employee 2 if they did not work at all in week 1 or 2, so the table should print 0 for Hours Worked, and 0 for Total Pay if I decide not to enter the ID, week number, and hours worked. Instead, however, it gives me an outOfBoundsException: Index: 1 Size: 1 Error when I try to do this. I was wondering if anyone had a solution to this. The 3 classes of my code are posted below. An example of the executed program with the outOfBoundsException is given in the main class.
import java.util.Scanner;
import java.util.ArrayList;
/**
* A class that contains methods for prompting a user for ACME employee information including names, tax IDs, and wages.
*/
public class EmployeeRecord
{
// ArrayLists used in methods.
ArrayList<String> employees = new ArrayList<String>();
ArrayList<String> tIds = new ArrayList<String>();
ArrayList<Double> wages = new ArrayList<Double>();
ArrayList<String> employeesLast = new ArrayList<String>();
Scanner in = new Scanner(System.in);
// Private Instance variables used in methods.
private String employeeId = "%03d";
private String employeeName = " ";
private String employeeNameLast = " ";
private String taxId = " ";
private double wage = 0.0;
/**
* A method that prompts the user to enter ACME employee names, tax IDs, and wages. This method also generates an ID number for each employee.
*/
public void setEmployeeInfo()
{
System.out.println("Please enter the names of each ACME employee, each employee tax ID, and each employee wage rate. Press Q when you are done entering names.");
while(!employeeName.equalsIgnoreCase("Q"))
{
employeeName = in.next();
if(employeeName.equalsIgnoreCase("Q"))
{
break;
}
employeeNameLast = in.next();
taxId = in.next();
wage = in.nextDouble();
employees.add(employeeName);
employeesLast.add(employeeNameLast);
tIds.add(taxId);
wages.add(wage);
System.out.println("Employee ID | Employee Name | Tax ID | Wage");
for(int i = 1; i <= employees.size(); i++)
{
System.out.printf(String.format(employeeId, i) + " | " + employees.get(i - 1) + " " + employeesLast.get(i - 1) + " | " + tIds.get(i - 1) + " | " + "%1.2f",wages.get(i - 1));
System.out.println();
}
}
}
/**
* A method that gets the list of ACME employee first names added to the record.
* #return
* Returns the ArrayList containing the first names of each employee entered.
*/
public ArrayList<String> getEmployeeArrayList()
{
return employees;
}
/**
* A method that gets the list of ACME employee last names added to the record.
* #return
* Returns the ArrayList containing the last names of each employee entered.
*/
public ArrayList<String> getEmployeeLastArrayList()
{
return employeesLast;
}
/**
* A method that gets the list of ACME employee tax IDs added to the record.
* #return
* Returns the ArrayList containing the tax IDs of each tax ID entered.
*/
public ArrayList<String> getTaxIdsArrayList()
{
return tIds;
}
/**
* A method that gets the list of ACME employee wages added to the record.
* #return
* Returns the ArrayList containing the wages of each wage entered.
*/
public ArrayList<Double> getWageArrayList()
{
return wages;
}
}
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
/**
* A class that contains methods for entering payroll information for each ACME employee. This class uses methods from the EmployeeRecord class in order to run and therefore, relies on the EmployeeRecord class to operate.
*/
public class Employee
{
// ArrayLists that will implement return methods from the EmployeeRecord class.
ArrayList<String> eMp;
ArrayList<String> eMpL;
ArrayList<Double> eW;
// ArrayLists used to store values in setEmployeePayroll() method.
ArrayList<Integer> eId = new ArrayList<Integer>();
ArrayList<Double> hours = new ArrayList<Double>();
ArrayList<Double> tPay = new ArrayList<Double>();
// Instance Variables used in setEmployeePayroll() method.
private String employeeId = "%03d";
private int weekNumber = 0;
private double hoursWorked = 0.0;
private double hoursWorked2 = 0.0;
private int terminate = 1000;
private int i = 0;
Scanner in = new Scanner(System.in);
/**
* A method that implements the EmployeeRecord class to prompt the user to enter information for the payroll of each ACME employee. The payroll for each employee is then displayed.
*/
public void setEmployeePayroll()
{
// Constructs a new EmployeeRecord to implement classes from EmployeeRecord class.
EmployeeRecord e = new EmployeeRecord();
e.setEmployeeInfo();
eMp = e.getEmployeeArrayList();
eMpL = e.getEmployeeLastArrayList();
eW = e.getWageArrayList();
// Local variables used in this method.
double totalPay = 0.0;
double totalHours = 0.0;
double overTime = 0.0;
double overTime2 = 0.0;
System.out.println("Please enter ACME employee ID, the week they worked (1 or 2), and the number of hours worked. This information should be entered in the order the names were entered. Enter 0 when you are done inputing information.");
while(terminate != 0)
{
terminate = in.nextInt();
if(terminate == 0)
{
break;
}
weekNumber = in.nextInt();
if(weekNumber == 1)
{
hoursWorked = in.nextDouble();
}
else if(weekNumber == 2)
{
hoursWorked2 = in.nextDouble();
}
// Checks to see if an employee receives a 150% bonus on their payroll.
if(hoursWorked > 0 && hoursWorked <= 40 && hoursWorked2 > 0 && hoursWorked2 <= 40)
{
totalHours = hoursWorked + hoursWorked2;
hours.add(totalHours);
totalPay = totalHours * (eW.get(i - 1));
tPay.add(totalPay);
hoursWorked = 0.0;
hoursWorked2 = 0.0;
}
else if(hoursWorked2 > 40 && hoursWorked > 0 && hoursWorked <= 40)
{
overTime2 = hoursWorked2 - 40;
totalHours = hoursWorked + hoursWorked2;
hours.add(totalHours);
totalPay = totalHours * (eW.get(i - 1)) + (overTime2 * 1.5);
tPay.add(totalPay);
hoursWorked = 0.0;
hoursWorked2 = 0.0;
}
else if(hoursWorked > 40 && hoursWorked2 <= 40 && hoursWorked2 > 0)
{
overTime = hoursWorked - 40;
totalHours = hoursWorked + hoursWorked2;
hours.add(totalHours);
totalPay = totalHours * (eW.get(i - 1)) + (overTime * 1.5);
tPay.add(totalPay);
hoursWorked = 0.0;
hoursWorked2 = 0.0;
}
else if(hoursWorked > 40 && hoursWorked2 > 40)
{
overTime = hoursWorked - 40;
overTime2 = hoursWorked2 - 40;
totalHours = hoursWorked + hoursWorked2;
hours.add(totalHours);
totalPay = totalHours * (eW.get(i - 1)) + (1.5 * (overTime + overTime2));
tPay.add(totalPay);
hoursWorked = 0.0;
hoursWorked2 = 0.0;
}
i = terminate;
}
// Constructs a new date format for the date of the payroll.
DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date d = new Date();
// Gets current date and time for payroll.
System.out.println("ACME Payroll run on " + format.format(d));
System.out.println();
System.out.println("Employee Number | Employee Name | Hours Worked | Total Pay");
for(int i = 1; i <= e.getEmployeeArrayList().size(); i++)
{
System.out.println(String.format(employeeId, i) + " | " + eMp.get(i - 1) + " " + eMpL.get(i - 1) + " | " + hours.get(i - 1) + " | " + tPay.get(i - 1));
}
}
}
/**
* The main class that runs the contents of the EmployeeRecord and Employee classes.
*
*
*/
public class runPayroll
{
public static void main(String[] args)
{
Employee eE = new Employee();
eE.setEmployeePayroll();
}
}
/**
* Please enter the names of each ACME employee, each employee tax ID, and each employee wage rate. Press Q when you are done entering names.
Jane Smith 1010101 10
Employee ID | Employee Name | Tax ID | Wage
001 | Jane Smith | 1010101 | 10.00
John Smith 1111111 10
Employee ID | Employee Name | Tax ID | Wage
001 | Jane Smith | 1010101 | 10.00
002 | John Smith | 1111111 | 10.00
q
Please enter ACME employee ID, the week they worked (1 or 2), and the number of hours worked. This information should be entered in the order the names were entered. Enter 0 when you are done inputing information.
1 1 20
1 2 30
0
ACME Payroll run on 2015/09/15 22:25:19
Employee Number | Employee Name | Hours Worked | Total Pay
Exception in thread "main" 001 | Jane Smith | 50.0 | 500.0
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at Employee.setEmployeePayroll(Employee.java:128)
at runPayroll.main(runPayroll.java:11)
*/

The problem exists at the bottom of the Employee class.
for(int i = 1; i <= e.getEmployeeArrayList().size(); i++)
{
System.out.println(String.format(employeeId, i) + " | " + eMp.get(i - 1) + " " + eMpL.get(i - 1) + " | " + hours.get(i - 1) + " | " + tPay.get(i - 1));
}
ArrayList is a zero-indexed list.
In short, imagine that you were to lay out all elements of a list as most people would think a list is:
1 2 3 4 5 6 7 8 9
That is a one-indexed list. A zero-indexed list (the type used in computer programming) is laid out like this:
0 1 2 3 4 5 6 7 8
If you want to access the first element, you have to get the element at position 0. If you want to get the 5th element, you have to get the element at position 4. It's a little backwards, but that's the way it's been for years, and it makes sense after dealing with lists and arrays for a while. For reasons why zero-indexed arrays are used, see here.
As for the code, you are trying to access it like a one-indexed list:
for(int i = 1; i <= e.getEmployeeArrayList().size(); i++)
There's only one entry in your list, so it looks like this:
0
The for loop starts iterating. It starts at int i = 1. Minor problem: there is no 1 index in the array. Java doesn't know what to do with it, so it blows up. To deal with a zero-indexed list, you should use
for(int i = 0; i < e.getEmployeeArrayList().size(); i++)

Related

Sales receipt, multiple choices (if/else), while loop, customer ability to change selections

None of the other posts seemed to fit accordingly.
I'm really struggling with producing this program without errors. I've come up with this below, however, if you run the program it is not adequately looping and if you choose the same candy twice the math isn't adding to the previous selection.
For the second part, I need to recode to adjust so that the customer may change the current selections if they'd like. So, I need the first part running perfectly.
import java.util.Scanner; //Program uses Scanner
import java.util.Calendar; //Program uses calendar
public class ClairAndreaG005PA2
{//Begin class ClairAndreaG005PA2
public static void main(String[] args)
{
/**Begin method. The customer is asked whether to proceed with a candy purchase.
* As long as the candy choice is in the proper range, prompt for the quantity,
* calculate the item total and subtotal; otherwise, print an error message. If it’s
* the first item in the purchase, ass it to the sales, a receipt with a $ sign for the
* item total. If not format the item without a $ sign for the item total
* and add it to the sales receipt. Start the process again when the customer wants
* to add another candy purchase. When the customer is done, the sales tax and the
* total calculated, the sales receipt is finalized and printed.
*/
int quantity = 0,
formatFirstItem = 1,
choice = 0;
final double TAX_RATE = .0825; //tax rate declared
double price = 0,
itemTotal = 0,
subtotal = 0,
taxAmount = 0,
total = 0;
char proceed = ' '; //proceed variable for loop
String candy = new String();
Calendar dateTime = Calendar.getInstance(); //situational date and time
Scanner input = new Scanner(System.in);
String salesReceipt = String.format("%n%nFAIRYTALE SWEETS%n"
+ "North Star Mall%n"
+ "San Antonio, TX%n"
+ "Date: %n", dateTime
+ "Time: %n", dateTime);
//Initiating variables and calculations
System.out.printf("%nDo you want to proceed with your candy purhase? \'Y\' or \'N\': ");
proceed = input.nextLine().charAt(0);
//End Prompt 1
while(Character.toUpperCase(proceed) == 'Y')
{
System.out.printf("%nFAIRYTALE SWEETS"
+ "%n%n1. Arabian Nights Chocolate Coins - 1 lb. Bag %5s%,7.2f"
+"%n2. Beauty and the Beast Lollipops - 1 lb. Bag %,12.2f"
+"%n3. Mad Hatter Jelly Beans - 1 lb. Bag %,20.2f"
+"%n4. Pinocchio's Candy Cones - Each %,23.2f"
+"%n5. Sleeping Beauty Caramel Apples - Each %,17.2f"
+"%n%nEnter your choice: ", "$", 2.25, 2.50, 1.75, 0.75, 1.25);
choice = input.nextInt();
//Prompt 2 Candy Menu
if(choice > 0)
{if(choice < 6)
{if(choice == 1)
{candy = "Arabian Nights Chocolate Coins";
price = 2.25;
}
else
{if(choice == 2)
{ candy = "Beauty and the Beast Lollipops";
price = 2.50;
}
else
{if(choice == 3)
{candy = "Mad Hatter Jelly Beans";
price = 1.75;
}
else
{if(choice == 4 )
{candy = "Pinocchio's Candy Cones";
price = 0.75;
}
else
{candy = "Sleeping Beauty Caramel Apples";
price = 0.75;
}
}
}
}
System.out.printf("%nQuantity for %s: ", candy);
quantity = input.nextInt();
//quantity of selections
}
else
{ System.out.println("Invalid candy choice! Try again.");
}
//Choices and selections
itemTotal = quantity * price; //calculation 1
subtotal += itemTotal; //calculation 2
System.out.printf("%nWould you like to make another candy purchase? \'Y\' or \'N\': ");
proceed = input.next().charAt(0);
if(formatFirstItem == 1 )
{
salesReceipt += String.format("%n%s"
+ "%n %d # $%.2f ex. %-24s $%,10.2f%n", candy,
quantity, price, " ", itemTotal);
formatFirstItem = 0;
}
else
{
salesReceipt += String.format("%s"
+ "%n %d # $%.2f ea. %-25s %,10.2f%n", candy,
quantity, price, " ", itemTotal);
}
//End if FormatFIrst Item is 1 or else formatFirstItem NOT 1
}
}//End while loop selection
taxAmount = TAX_RATE * subtotal;// calculation 3
total = taxAmount + subtotal; // calculation 4
salesReceipt += String.format("%n%36s %-6s $%,10.2f"
+ "%n%36s %-7s %,10.2f"
+ "%n%n%36s %-6s $%,10.2f%n", "SUBTOTAL: ", " ",
subtotal, "TAX # 8.250%: ", " ", taxAmount,
"TOTAL: ", " ", total);
System.out.printf("%s", salesReceipt);
}
}
Let me know!

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;
}
}
}

Java - For loop (do/while) repeats indefinitely

I have been working on a project for my course. It's a simple salary calculator, which I have figured out fairly easily and it functions flawlessly. It also takes into consideration benchmarks for commission. I have completed choped on the last part, however. I cannot get it to function. It either loops indefinitely, or it generates static numbers under the "Total Compensation" column (they should be dynamic based on commission etc).
Bob makes $85,000 a year.
He gets no bonus/commission if he sells less than $120,000
He gets 15% commission if his sales for the year are >= $120,000
He gets an additional 2% for every $150k in sales (150k, 300k, 450k
etc)
User inputs a sales number (example: $300,000).
Program calculates BaseSalary + ($300,000 * .15) + ($300,000 * .02)
Potential Sales on the left and then Total Compensation on the right side
200,000 ----------------------> (Calculated)
220,000 ----------------------> (Calculated)
240,000 ----------------------> (Calculated)
260,000 ----------------------> (Calculated)
280,000 ----------------------> (Calculated)
300,000 ----------------------> (Calculated)
//Variables defined here
double Sales = input.nextDouble();
double TotalCompensation;
int Commission;
double CommissionRate;
double AcceleratedCommissionRate;
int BaseSalary;
double TargetSales;
double Accelerator;
double AcceleratorGoal;
double AcceleratedCommission;
// Mathematical Operations
Accelerator = 0.80;
TargetSales = 150000;
CommissionRate = 0.15;
AcceleratedCommissionRate = ((CommissionRate) * (2.0));
BaseSalary = 85000;
Commission = (int) (Sales * CommissionRate);
AcceleratedCommission = (double) (Sales * AcceleratedCommissionRate);
AcceleratorGoal = (double) 120000;
// If Else Logic Flow
if(Sales < AcceleratorGoal)
{
TotalCompensation = BaseSalary;
System.out.print("\nCommission Goal HAS NOT been met");
System.out.println("\nTotal annual compensaton is: ");
System.out.println(numberFormat.format(TotalCompensation));
}
else if(Sales < TargetSales)
{
TotalCompensation = BaseSalary + Commission;
System.out.print("\nCommission Goal HAS been met");
System.out.println("\nTotal annual compensaton is: ");
System.out.println(numberFormat.format(TotalCompensation));
}
else if(Sales >= TargetSales)
{
TotalCompensation = BaseSalary + AcceleratedCommission;
System.out.print("\nAccelerator Goal HAS been met");
System.out.println("\nTotal annual compensaton is: ");
System.out.println(numberFormat.format(TotalCompensation));
}
// Potential Commission Structure Table
double PotentialSales;
double EndLoop = (Sales * 1.5);
int Increment = 20000;
System.out.println("\nPotential Sales\t\tTotal Compensation");
for (PotentialSales = Sales; PotentialSales < EndLoop;
PotentialSales = PotentialSales += Increment)
{
do
{
String output = numberFormat.format(PotentialSales) + "\t\t"
+ numberFormat.format(BaseSalary);
System.out.println(output);
}
while(PotentialSales < AcceleratorGoal);
do
{
String output = numberFormat.format(PotentialSales) + "\t\t"
+ numberFormat.format(Commission + BaseSalary);
System.out.println(output);
}
while(PotentialSales >= AcceleratorGoal && PotentialSales < TargetSales);
do
{
String output = numberFormat.format(PotentialSales) + "\t\t"
+ numberFormat.format(AcceleratedCommission + BaseSalary);
System.out.println(output);
}
while(PotentialSales >= TargetSales);
}
Any suggestions or tips whatsoever would be a lifesaver.
This code will iterate until expression (PotentialSales < AcceleratorGoal) is false. As you are not updating the value of PotentialSales & AcceleratorGoal in the body of do{..body..}while(expression), it will iterate indefinitely if (PotentialSales < AcceleratorGoal) is true at first place, otherwise it will get executed once and will go to the next statement after the while condition.
Code
do{
String output = numberFormat.format(PotentialSales) + "\t\t" + numberFormat.format(BaseSalary);
System.out.println(output);
}while(PotentialSales < AcceleratorGoal);
You might want to update the PotentialSales or AcceleratorGoal Value inside the body of do while loop or change condition w.r.t output variable.
Same goes for next two do..while loops.
Your do while loop repeats infinitely because,you are not updating the value of PotentialSales in do while loop
To understand the problem,check the following code
int accelerationsales=5;
for(int potentialsales=0;potentialsales<5;potentialsales=potentialsales+=1) {
do {
System.out.println("Hello");
} while(potentialsales<accelerationsales);
}
Run this sample code,you will understand the problem.

Process validated information of 7 employees according to example console interaction

Big breath lol
So, in my college programming class for Java, we need to create a program
that process first, last, regular-hours, sick-hours, and the hourly wage for
an assumed 7 employees. I'm almost positive my professor is trying to stress
more object-oriented programming and the use of enumerated data types in this
project. Luckily, our merciful master offered an example of the console interaction shown here:
Employee #1:
Enter the employee’s first name: XXXXXXX
Enter the employee’s last name: XXXXXXX
Enter the number of hours worked: XX.XX
Enter the number of vacation/sick hours: XX.XX
Enter the hourly wage: XX.XX
Employee #2:
Enter the employee’s first name: XXXXXXX
Enter the employee’s last name:
Invalid! The employee’s name must be at least on character long.
Enter the employee’s last name: XXXXXXX
Enter the number of hours worked: -10.00
Invalid! The hours worked must be between 0 and 80 hours.
Enter the number of hours worked: XX.XX
Enter the number of vacation/sick hours: XX.XX
Enter the hourly wage: XX.XX
…
Name Hours V/S Gross Pay Tax Take-Home
XXXXXXX, XXXXXXX XX.XX XX.XX XXXX.XX XXXX.XX XXXX.XX
XXXXXXX, XXXXXXX XX.XX XX.XX XXXX.XX XXXX.XX XXXX.XX
…
Total XXXX.XX XXXX.XX XXXXXX.XX XXXXXX.XX XXXXXX.XX
I have each of the validating methods finished, and we are only required to
use 2 classes, Driver and Employee with whatever static methods we think
we should use showing care for efficiency. My classes are currently as follows:
Driver Class
package project2;
import java.util.Scanner;
/**
* This program calculates an employee's weekly
* take-home wages based on the number of hours
* and the hourly wage.
* #author ***********
*
*/
public class Driver
{
// Employee's First Name
static String firstName;
//Employee's Last Name
static String lastName;
//The amount of regular hours worked
static int regHours;
//The amount of vacation/sick hours
static int vsHours;
//The hourly wage of pay
static float wage;
//The deducted tax
static String taxDeduction;
//Total pay to take home
static String takeHome;
//Number of employees (assumed)
static final int iters = 7;
/**
* Manages interaction with user
* throughout program.
* #param args
*/
public static void main(String[] args)
{
Scanner keyboard = new Scanner ( System.in );
}
/**
* Checks to see if there is an
* alphabetical character in
* an employee's name.
*/
public static boolean validName ( String name )
{
boolean hasOneAlpha = name.matches(".[a-zA-Z]+.*");
return hasOneAlpha;
}
/**
* Validates the regular hours of an
* employee to not be greater than 80
* hours.
*/
public static boolean validHours ( int hours )
{
if ( hours > 80 )
return false;
else
return true;
}
/**
* Validates the sick or vacation hours
* of an employee to not be greater than
* 40 hours.
*/
public static boolean validSick ( int vsHours )
{
if ( vsHours > 40 )
return false;
else
return true;
}
/**
* Validates the wage of an employee
* to ensure the wage is less than $100/hr
* and not less than or equal to 0.
*/
public static boolean validWage ( float wage )
{
if ( wage > 100.00 || wage <= 0.0 )
return false;
else
return true;
}
}
And my Employee Class:
package project2;
public class Employee
{
String firstName;
String lastName;
int regHours;
int vsHours;
float wage;
static float earnings;
float tax;
public Employee(String firstName, String lastName, int regHours,
int vsHours, float wage)
{
this.firstName = firstName;
this.lastName = lastName;
this.regHours = regHours;
this.vsHours = vsHours;
this.wage = wage;
}
/**
* Establishes tax rate based on
* earnings.
* #return
*/
public float taxDeduction()
{
earnings = totalPay();
if ( earnings > 900 )
tax = (float) 0.15;
else if ( earnings >= 300 )
tax = (float) 0.13;
else
tax = (float) 0.11;
return ( earnings * tax );
}
/**
* Calculates the net pay after
* a tax deduction.
*/
public float netPay()
{
earnings = totalPay();
float taxDeduction = taxDeduction();
return ( earnings - taxDeduction );
}
/**
* Calculates the total amount paid
* to the employee.
*/
public float totalPay()
{
int totalHours = ( regHours + vsHours );
if (( vsHours <= 20 ) && ( totalHours > 40 ))
if ( totalHours - 40 >= vsHours )
earnings = (float) (( 40 * wage) + (( totalHours - 40 - vsHours ) * 1.5 * wage) + (( vsHours ) * 1.25 * wage ));
else
earnings = (float) (( 40 * wage ) + (( totalHours - 40 ) * 1.25 * wage ));
else if ( regHours > 40 )
earnings = (float) ( totalHours * wage + ( regHours - 40 ) * .5 * wage );
else
earnings = totalHours * wage;
return earnings;
}
}
I guess what im really asking, is how do i iterate through employees, process
the information for each of them respectively, and output each Employee object
with a row specifically for total. Criticize away, still learning. I'll have more time off of work to study more often but, unfortunately, that's after my due date :(
I sincerely thank anyone who was able to read this all and any help is greatly appreciated! Sharing knowledge is after all the purpose of life. <3CS
The below sudo can work with some modifications In your main method
for(int i=0;i<iters;i++)
fname <- read
while(validName(fname) != true)
fname <- read
lname <- read
while(validName(lname) != true)
lname <- read
regHours <- read
while(validHours(regHours) != true)
regHours <- read
// like that write for the remaining properties
Employee emp = new Employee(firstName,lastName,regHours,vsHours,wage)
System.out.println("Name Hours V/S Gross Pay Tax Take-Home");
// get what ever you want according to your logic like emp.taxDeduction()
System.out.prinltln("Total ")
System.out.println(emp.totalPay())

Basic Java control structure issue.

I'm a college freshmen and I'm having trouble with my programming homework. The homework I got from my lecturer was for me to write a program in Java to take in a student's info, and allow the student to choose how many subject the student takes, and input marks and credit hours, followed by a formula to calculate the grade and subject grade points. In the end of the program, the program would be able to output the student info (name, ID etc) and the total subject grade point for all of the subjects entered, total credit hours for all the subjects, and the cumulative grade point average (CGPA).
However, I have three problems here
I have an issue with the loop that I have set in order to read how many subjects the user wants to key in.
When I tried to print "Grade = " + subjectGrade); my compiler says it hasn't been initialized. Same goes to the GradePoint and subjectCreditHour.
And I couldn't figure out how to get the program to calculate the Total Subject Grade Points, Total Credit Hours, and CGPA. Because depending on how many numbers of subjects the user wants, I can't figure out how to get the program to take in the user's input and sum them up together
My code goes like this :
package javaquiz1;
import java.util.Scanner;
/**
*
* #author jerem_000
*/
public class JavaQuiz1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner (System.in);
String name;
int ID;
int tel;
String email;
int subjects;
String subjectName;
int subjectCreditHour;
int subjectMark;
String subjectGrade;
double GradePoint;
double subjectGradePoint;
double CGPA;
double totalSubjectGP;
int totalCreditHour;
System.out.print("Please input student's name : ");
name = input.nextLine();
System.out.print("Please input student's ID : ");
ID = input.nextInt();
System.out.print("Please input student's telephone number : ");
tel = input.nextInt();
System.out.print("Please input student's email : ");
email = input.next();
System.out.print("Please input number of subjects : ");
subjects = input.nextInt();
for (int i = 1; i >= subjects ; i++) { //I'm having an issue with this loop
System.out.println("Subject " + i + " : Please input the following"); //I placed the variable i there in order to make the program print something like "Subject 1 , Subject 2, Subject 3 etc". Depending on the user's number of subjects input
System.out.print("Subject name : ");
subjectName = input.next();
System.out.print("Credit Hour : ");
subjectCreditHour = input.nextInt();
System.out.print("Mark : ");
subjectMark = input.nextInt();
if ( subjectMark >= 80 ) {
subjectGrade = "A";
GradePoint = 4.0;
} else if (subjectMark < 80) {
subjectGrade = "B+";
GradePoint = 3.5;
} else if (subjectMark < 70) {
subjectGrade = "B";
GradePoint = 3.0;
} else if (subjectMark < 65) {
subjectGrade = "C+";
GradePoint = 2.5;
} else if (subjectMark < 55) {
subjectGrade = "C";
GradePoint = 2.0;
} else if (subjectMark < 50) {
subjectGrade = "D";
GradePoint = 1.0;
} else {
subjectGrade = "F";
GradePoint = 0.0;
}
}
System.out.println("Grade = " + subjectGrade);
System.out.println("Subject Grade Point = " + (GradePoint * subjectCreditHour)); //I'm having a problem with the subjectGrade, GradePoint, and subjectCreditHour, it says variable might have not been initialized
System.out.println("Name : " + name);
System.out.println("ID : " + ID);
System.out.println("Tel : " + tel);
System.out.println("email : " + email);
System.out.print("Total subject Grade Points = " );
System.out.print("Total Credit Hours = " );
System.out.print("Cumulative Grade Point Average ="); //On this 3 system.out.prints, I can't seem to think of a way to read the Grade Point, Total Credit Hours, and CGPA, and add them all together
}
}
I also have a sample output on how the program is supposed to be:
Please input student's name : James Cook
Please input student's ID : 0106578
Please input student's tel : 010783938
Please input student's e-mail : jcook#gmail.com
Please input number of subjects : 3
Subject 1 : Please input the following
Subject name : Fundamentals of Programming
Credit Hour : 4
Mark : 78
Grade : B+
Subject Grade Point : 14.0
Subject 2 : Please input the following
Subject name : English
Credit Hour : 3
Mark : 85
Grade : A
Subject Grade Point : 12.0
Subject 3 : Please input the following
Subject name : Computer Fundamentals
Credit Hour : 3
Mark : 78
Grade : B+
Subject Grade Point : 10.5
Name : James Cook
ID : 0106578
tel : 010783938
e-mail : jcook#gmail.com
Total subject Grade Point = 36.5
Total Credit Hours = 10
CGPA = 3.65
The formula to calculate the subject grade point is
subjectGradePoint = GradePoint * CreditHour
And the formula to calculate the CGPA (cumulative grade point average) is
CGPA = totalSubjectGP / totalCreditHours
Correction, criticism, advice will be welcomed for future improvement. Thanks in advance!
1) I have an issue with the loop that I have set in order to read how
many subjects the user wants to key in.
Already answered by #Nishan in a comment. Just replace for (int i=1;i >= subjects; i++) by for (int i=1;i <= subjects; i++).
2) When I tried to print "Grade = " + subjectGrade); my compiler says it
hasn't been initialized. Same goes to the GradePoint and
subjectCreditHour.
Already answered.
3) And I couldn't figure out how to get the program to calculate the
Total Subject Grade Points, Total Credit Hours, and CGPA. Because
depending on how many numbers of subjects the user wants, I can't
figure out how to get the program to take in the user's input and sum
them up together
You already are on the right way since you have the accumulators you need:
double subjectGradePoint = 0d;
double CGPA = 0d;
double totalSubjectGP = 0d;
int totalCreditHour = 0;
Whitin your loop and after nested if-else blocks, you need to update subjectGradePoint, totalSubjectGP and totalCreditHour variables in each iteration:
subjectGradePoint = GradePoint * CreditHour;
totalSubjectGP += subjectGradePoint;
totalCreditHour += CreditHour;
Finally, after your loop calculate CGPA:
CGPA = totalSubjectGP / totalCreditHour;
Java mandates method variables to be initialized before use,
just initialize String value and it shall work fine. Please refer to below code extract.
String subjectName=null;
int subjectCreditHour=0;
String subjectGrade=null;
java variable must intialized before use
import java.util.Scanner;
/**
*
* #author jerem_000
*/
public class JavaQuiz1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner (System.in);
String name;
int ID;
int tel;
String email;
int subjects;
String subjectName;
int subjectCreditHour=0;
int subjectMark;
String subjectGrade="";
double GradePoint=0;
double subjectGradePoint=0;
double CGPA;
double totalSubjectGP;
int totalCreditHour;
System.out.print("Please input student's name : ");
name = input.nextLine();
System.out.print("Please input student's ID : ");
ID = input.nextInt();
System.out.print("Please input student's telephone number : ");
tel = input.nextInt();
System.out.print("Please input student's email : ");
email = input.next();
System.out.print("Please input number of subjects : ");
subjects = input.nextInt();
for (int i = 1; i >= subjects ; i++) { //I'm having an issue with this loop
System.out.println("Subject " + i + " : Please input the following"); //I placed the variable i there in order to make the program print something like "Subject 1 , Subject 2, Subject 3 etc". Depending on the user's number of subjects input
System.out.print("Subject name : ");
subjectName = input.next();
System.out.print("Credit Hour : ");
subjectCreditHour = input.nextInt();
System.out.print("Mark : ");
subjectMark = input.nextInt();
if ( subjectMark >= 80 ) {
subjectGrade = "A";
GradePoint = 4.0;
} else if (subjectMark < 80) {
subjectGrade = "B+";
GradePoint = 3.5;
} else if (subjectMark < 70) {
subjectGrade = "B";
GradePoint = 3.0;
} else if (subjectMark < 65) {
subjectGrade = "C+";
GradePoint = 2.5;
} else if (subjectMark < 55) {
subjectGrade = "C";
GradePoint = 2.0;
} else if (subjectMark < 50) {
subjectGrade = "D";
GradePoint = 1.0;
} else {
subjectGrade = "F";
GradePoint = 0.0;
}
}
System.out.println("Grade = " + subjectGrade);
System.out.println("Subject Grade Point = " + (GradePoint * subjectCreditHour)); //I'm having a problem with the subjectGrade, GradePoint, and subjectCreditHour, it says variable might have not been initialized
System.out.println("Name : " + name);
System.out.println("ID : " + ID);
System.out.println("Tel : " + tel);
System.out.println("email : " + email);
System.out.print("Total subject Grade Points = " );
System.out.print("Total Credit Hours = " );
System.out.print("Cumulative Grade Point Average ="); //On this 3 system.out.prints, I can't seem to think of a way to read the Grade Point, Total Credit Hours, and CGPA, and add them all together
}
}

Categories

Resources