ArrayList out of Bounds Exception? PayRoll Class - java

I have a project in my programming class that has to give a PayRoll scenario which contains three classes including PayRoll, PayRollTester, and EmployeeRecord. My code compiles and prints the EmployeeRecord correctly but does not list the PayRoll correctly. Instead, I receive an error saying Error: Out of Bounds of ArrayList.
Payroll:
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Date;
// ...javadoc...
public class Payroll
{
//ArrayLists that will use methods from EmployeeRecords.
ArrayList<String> employeeNames2;
ArrayList<Double> employeeWages2;
ArrayList<Integer> emID = new ArrayList<Integer>();
ArrayList<Double> hours = new ArrayList<Double>();
ArrayList<Double> totalPay = new ArrayList<Double>();
//Creating the hours and wages variables.
private double hoursWorked = 0.0;
private double hoursWorked2 = 0.0;
private int weeks = 0;
private String employeeID = "%03d";
private int quit = 1000;
private int i = 1;
Scanner input = new Scanner(System.in);
public void setEmployeePayroll()
{
// Constructs a new EmployeeRecord.
EmployeeRecord e = new EmployeeRecord();
e.setEmployeeInfo();
employeeNames2 = e.getEmployeeNamesArrayList();
employeeWages2 = e.getWageArrayList();
// Local variables used in setEmployeePayroll.
double totalPay2 = 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(quit != 0)
{
quit = input.nextInt();
if(quit == 0)
{
break;
}
weeks = input.nextInt();
if(weeks == 1)
{
hoursWorked = input.nextDouble();
}
else if(weeks == 2)
{
hoursWorked2 = input.nextDouble();
}
/*
* I am checking to see if the employee is going to be paid for overtime and also calculating the pay for both weeks.
* 1) My first if statement indicates whether or not the employee worked over 40 in week one and week two.
* 2) My first else if statement indicates whether the employee works more than 40 hours in week two but not week one.
* 3) My second else if statement indicates whether the employee works more than 40 hours in week one but not in week two.
* 3) My third else if statement finally indicates that the employee worked over 40 hours in both week one and two.
*/
if(hoursWorked > 0 && hoursWorked <= 40 && hoursWorked2 > 0 && hoursWorked2 <= 40)
{
totalHours = hoursWorked + hoursWorked2;
hours.add(totalHours);
totalPay2 = totalHours * (employeeWages2.get(i - 1));
totalPay.add(totalPay2);
hoursWorked = 0.0;
hoursWorked2 = 0.0;
}
else if(hoursWorked2 > 40 && hoursWorked > 0 && hoursWorked <= 40)
{
overTime2 = hoursWorked2 - 40;
totalHours = hoursWorked + hoursWorked2;
hours.add(totalHours);
totalPay2 = totalHours * (employeeWages2.get(i - 1)) + (overTime2 * 1.5);
totalPay.add(totalPay2);
hoursWorked = 0.0;
hoursWorked2 = 0.0;
}
else if(hoursWorked > 40 && hoursWorked2 <= 40 && hoursWorked2 > 0)
{
overTime = hoursWorked - 40;
totalHours = hoursWorked + hoursWorked2;
hours.add(totalHours);
totalPay2 = totalHours * (employeeWages2.get(i - 1)) + (overTime * 1.5);
totalPay.add(totalPay2);
hoursWorked = 0.0;
hoursWorked2 = 0.0;
}
else if(hoursWorked > 40 && hoursWorked2 > 40)
{
overTime = hoursWorked - 40;
overTime2 = hoursWorked2 - 40;
totalHours = hoursWorked + hoursWorked2;
hours.add(totalHours);
totalPay2 = totalHours * (employeeWages2.get(i - 1)) + (1.5 * (overTime + overTime2));
totalPay.add(totalPay2);
hoursWorked = 0.0;
hoursWorked2 = 0.0;
}
i = quit;
}
System.out.println();
System.out.println("Employee Number | Employee Name | Hours Worked | Total Pay");
for(int i = 0; i < e.getEmployeeNamesArrayList().size();)
{
System.out.println(String.format(employeeID, i + 1) + " | " + emID.get(i + 1) + " | " + hours.get(i + 1) + " | " + totalPay.get(i + 1));
}
}
}
EmployeeRecord:
import java.util.Scanner;
import java.util.ArrayList;
// ...javadoc...
public class EmployeeRecord
{
/*
* Creating the array and instance variables for EmployeeRecord consisting
* of TaxID numbers, Employee Names, Wages, Employee ID numbers and hours worked.
*/
ArrayList<String> employeeNames = new ArrayList<String>();
ArrayList<String> taxIDList = new ArrayList<String>();
ArrayList<Double> employeeWages = new ArrayList<Double>();
Scanner input = new Scanner(System.in);
private String employeeID = "%03d";
private String employeeFullName = " ";
private String taxID = " ";
private double wage = 0.0;
//Adding employees.
public void setEmployeeInfo()
{
System.out.println("Please enter the full names of each ACME employee, their employee tax ID, and their employee wage rate. Type 'Q Q' when you are done entering employee information.");
while(employeeFullName != "Q")
{
employeeFullName = input.next() + " " + input.next();
if(employeeFullName.equalsIgnoreCase("Q" + " " + "Q"))
{
break;
}
taxID = input.next();
wage = input.nextDouble();
employeeNames.add(employeeFullName);
taxIDList.add(taxID);
employeeWages.add(wage);
System.out.println("Employee ID | Employee Name | Tax ID | Wage");
for(int i = 1; i <= employeeNames.size(); i++)
{
System.out.printf(String.format(employeeID, i) + " | " + employeeNames.get(i - 1) + " | " + taxIDList.get(i - 1) + " | " + "%1.2f",employeeWages.get(i - 1));
System.out.println();
}
}
}
/**
* Creating a method that returns the employee ArrayList employeeName.
*/
public ArrayList<String> getEmployeeNamesArrayList()
{
return employeeNames;
}
/**
* Creating a method that returns the employee's Tax ID ArrayList taxIDList.
*/
public ArrayList<String> getTaxIdsArrayList()
{
return taxIDList;
}
/**
* Creating a method that returns the wages ArrayList
*/
public ArrayList<Double> getWageArrayList()
{
return employeeWages;
}
}
PayrollTester:
import java.util.Scanner;
// ...javadoc...
public class PayrollTester
{
public static void main(String[] args)
{
Payroll employeeComplete = new Payroll();
employeeComplete.setEmployeePayroll();
}
}

ArrayList index starts from 0. since your for loop start i = 0, you cannot do (i+1) in accessing arrayList elements.
emID.get(i + 1)
and also the size of emID is always 0 because you have just create new Arraylist but not added any objects to that list.

Related

How can I put an if statement inside of a if-else if statement

I am trying to make a salary calculator that if the applicant is under 18, they cannot receive overtime, because in the state I am in the maximum allowed for minors is 18 hours. I have it set where you cannot earn overtime until you reach 40 hours. Is there anything I can do for this?
import java.util.Scanner;
public class SalaryV2
{
public static void main(String[] args)
{
//Declare and initialize variables
double totalSalary;
boolean isOvertime;
Scanner in = new Scanner(System.in);
//Input
System.out.print("Please enter your name (first last): ");
String firstName = in.next();
String lastName = in.nextLine();
System.out.print("Please enter your age: ");
String customerAge = in.nextLine();
double age = Double.parseDouble(customerAge);
System.out.print("\nWhat is your hourly rate of pay: ");
String rateOfPay = in.nextLine();
double payRate = Double.parseDouble(rateOfPay);
System.out.print("\nHow many hours did you work: ");
String totalHoursWorked = in.nextLine();
double totalHours = Double.parseDouble(totalHoursWorked);
System.out.println();
//Processing
if(17 > age)
{
isOvertime = false;
totalSalary = totalHours * payRate;
}
else if(totalHours > 40)
{
if(totalHours > 40)
{
isOvertime = true;
totalSalary = 40 * payRate + (totalHours - 40) * payRate * 1.5;
}
else
{
isOvertime = false;
totalSalary = totalHours * payRate;
}
}
//Output
System.out.print("Employee Name: " + lastName + ", " + firstName\n);
System.out.print("Hours worked: " + totalHours);
System.out.println("\t\tOvertime: " + isOvertime +);
System.out.println("Salary: " + totalSalary);
}
}
Keep it simple, no need for else-if-if,
import java.util.Scanner;
public class SalaryV2{
public static void main(String[] args){
//Declare and initialize variables
double totalSalary= 0;
boolean isOvertime = false;
Scanner in = new Scanner(System.in);
//Input
System.out.print("Please enter your name (first last): ");
String firstName = in.next();
String lastName = in.nextLine();
System.out.print("Please enter your age: ");
String customerAge = in.nextLine();
double age = Double.parseDouble(customerAge);
System.out.print("\nWhat is your hourly rate of pay: ");
String rateOfPay = in.nextLine();
double payRate = Double.parseDouble(rateOfPay);
System.out.print("\nHow many hours did you work: ");
String totalHoursWorked = in.nextLine();
double totalHours = Double.parseDouble(totalHoursWorked);
System.out.println();
//Processing
if(age >= 18 && totalHours > 40) {
isOvertime = true;
totalSalary = 40 * payRate + (totalHours - 40) * payRate * 1.5;
}else{
isOvertime = false;
totalSalary = totalHours * payRate;
}
//Output
System.out.print("Employee Name: " + lastName + ", " + firstName +'\n' );
System.out.print("Hours worked: " + totalHours + '\n');
System.out.println("Overtime: " + isOvertime );
System.out.println("Salary: " + totalSalary);
}}
With the following input STDIN
firstname lastname
19
10
42
Output :
$javac SalaryV2.java
$java -Xmx128M -Xms16M SalaryV2
Please enter your name (first last): Please enter your age:
What is your hourly rate of pay:
How many hours did you work:
Employee Name: lastname, firstname
Hours worked: 42.0
Overtime: true
Salary: 430.0
If under 18 STDIN
firstname lastname
17
10
42
Output :
$javac SalaryV2.java
$java -Xmx128M -Xms16M SalaryV2
Please enter your name (first last): Please enter your age:
What is your hourly rate of pay:
How many hours did you work:
Employee Name: lastname, firstname
Hours worked: 42.0
Overtime: false
Salary: 420.0
Checked by executing the above code.
If you are a minor you cannot get additional pay for any overtime you work (strange as that may seem).
If you have less than 40 hours you cannot get pay for overtime (everybody knows the weird consequences of that...).
So you can only get paid for overtime if you are over 18 and have more than 40 hours.
if((18 <= age) && (totalHours > 40))
{
isOvertime = true;
totalSalary = 40 * payRate + (totalHours - 40) * payRate * 1.5;
} else
{
isOvertime = false;
totalSalary = totalHours * payRate;
}
I.e. I do not see the need for nested ifs.
I didn't understand very well your question, but here is something you can improve.
In the first if, you are not considering even 17 years old, you should put if(17 >= age) or if(18 > age).
Then, in the else if you put the same condition as the if below, so what you should do is:
else if(totalHours > 40)
{
isOvertime = true;
totalSalary = 40 * payRate + (totalHours - 40) * payRate * 1.5;
}
else
{
isOvertime = false;
totalSalary = totalHours * payRate;
}
And to make your code more efficient, you can put two conditions in one if.
if(18 > age && totalHours > 40)
{
isOvertime = false;
totalSalary = totalHours * payRate;
}
else
{
isOvertime = true;
totalSalary = 40 * payRate + (totalHours - 40) * payRate * 1.5;
}
I didn't check if the code actually works, but it should be fine

Calculating employee pay with methods

I am having trouble with a part of an assignment where i have a method to calculate the regular pay of an employee but if the hours worked is over 40 then the rest is overtime but in if the user types in 50 hours with a 10 dollar rate it will print out 500 but i want it to to only print out 40 of those 50 hours and take the rest as overtime.
package paytime;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
String firstName, lastName, choice;
double hoursWorked, hourlyWage, weeklyPay;
Employee one = new Employee();
System.out.print("Enter Y to process employee or any other key to end: ");
choice = scn.nextLine();
if (choice.equalsIgnoreCase("Y"))
{
System.out.print("Enter employee number: ");
int number = scn.nextInt();
while (!one.findEmpNumber(number))
{
System.out.print("Invlaid, enter a proper employee number: ");
number = scn.nextInt();
}
System.out.print("Enter first name: ");
firstName = scn.next();
System.out.print("Enter last name: ");
lastName = scn.next();
System.out.print("Enter hours worked: ");
hoursWorked = scn.nextDouble();
while (hoursWorked < 0)
{
System.out.print("Negative hours not allowed. Enter hours worked: ");
hoursWorked = scn.nextDouble();
}
System.out.print("Enter hourly wage: $");
hourlyWage = scn.nextDouble();
while (hourlyWage < 0 || hourlyWage > 100)
{
System.out.print("Negative wage is not allowed or wage entered is to high. Enter hourley wage: $");
hourlyWage = scn.nextDouble();
}
System.out.println(" ");
if (hoursWorked <= 40.0)
{
System.out.println("Worker " + number + " Paycheck Information: ");
System.out.println("Name is: " + firstName + " " + lastName);
System.out.println("Weekly Pay is: " + one.callWeeklyPay(hoursWorked = 40, hourlyWage));
System.out.println("Income Taxes is: " + one.callIncomeTax());
System.out.println("Net Pay is: " + one.callNetPay());
}
else if (hoursWorked > 40.0)
{
System.out.println("Worker " + number + " Paycheck Information: ");
System.out.println("Name is: " + firstName + " " + lastName);
System.out.println("Weekly Pay is: " + one.callWeeklyPay(hoursWorked, hourlyWage));
System.out.println("Income Taxes is: " + one.callIncomeTax());
System.out.println("Net Pay is: " + one.callNetPay());
System.out.println(" ");
System.out.println(" ");
System.out.println("Worker " + number + " Overtime Calculation");
System.out.println("Name is: " + firstName + " " + lastName);
System.out.println("Weekly Pay is: " + one.callOvertimePay());
}
}
else
{
System.out.println("Total number of Employees processed: ");
}
}
}
package paytime;
public class Employee {
private int empNumbers [] = {101, 103, 106, 109, 110, 113, 116, 118, 120};
public double weeklyPay, hoursWorked, hourlyWage, incomeTax, netPay, actualOvertimeHours, overtimePay, overtimeHours;
public double overtimeWage = hourlyWage * 1.5;
public boolean findEmpNumber(int number)
{
boolean found = false;
for (int sub = 0; sub < empNumbers.length; sub++)
{
if (number == empNumbers[sub])
{
found = true;
break;
}
}
return found;
}
private void calculateWeeklyPay(double hoursWorked, double hourlyWage) {
weeklyPay = hoursWorked * hourlyWage;
}
public double callWeeklyPay(double hoursWorked, double hourlyWage) {
calculateWeeklyPay(hoursWorked, hourlyWage);
return weeklyPay;
}
private void calculateIncomeTax() {
if (weeklyPay > 0.0 && weeklyPay <= 300.0)
{
incomeTax = weeklyPay * 0.10;
}
else if (weeklyPay > 300.1 && weeklyPay <= 400.0)
{
incomeTax = weeklyPay * 0.12;
}
else if (weeklyPay > 400.1 && weeklyPay <= 500.0)
{
incomeTax = weeklyPay * 0.15;
}
else if (weeklyPay > 500.1)
{
incomeTax = weeklyPay * 0.20;
}
}
public double callIncomeTax() {
calculateIncomeTax();
return incomeTax;
}
private void calculateNetPay() {
netPay = weeklyPay - incomeTax;
}
public double callNetPay() {
calculateNetPay();
return netPay;
}
private void calculateOvertimePay() {
overtimeHours = hoursWorked -40;
overtimePay = ovetimeHours * overtimeWage;
}
public double callOvertimePay() {
calculateOvertimePay();
return overtimePay;
}
}
When you call callWeeklyPay method subtract 40 from the hoursWorked.
one.callWeeklyPay(hoursWorked - 40, hourlyWage));
But I would suggest moving the logic of checking for overtimes(hours exceeding 40) inside the Employee class (callWeeklyPay method) itself.

Getting "while expected" error in "do...while" loop

I keep getting this error and I am not stuck trying to fix it.
package bonuscalc;
import java.text.DecimalFormat;
import java.util.Scanner;
public class BonusCalc {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
DecimalFormat formatter = new DecimalFormat("#0.00");
int Salary;
double NewSal, Comm;
double p1 = 0.1;
double p2 = 0.15;
double p3 = 0.2;
double p4 = 0.3;
System.out.println("Welcome to Bonus Calculator");
do{
System.out.print("Enter your Salary: ");
Salary = input.nextInt();
}While (Salary < 0)
if((Salary > 0) && (Salary <= 8000)){
Comm = (Salary * p1);
NewSal = Salary + Comm;
System.out.print("Your Commition is RM" + formatter.format(Comm));
System.out.println(" and your New Salary is RM" + formatter.format(NewSal));
}
else if((Salary > 8000) && (Salary <= 15000)){
Comm = (Salary * p2);
NewSal = Salary + Comm;
System.out.print("Your Commition is RM" + formatter.format(Comm));
System.out.println(" and your New Salary is RM" + formatter.format(NewSal));
}
else if((Salary > 15000) && (Salary <= 25000)){
Comm = (Salary * p3);
NewSal = Salary + Comm;
System.out.print("Your Commition is RM" + formatter.format(Comm));
System.out.println(" and your New Salary is RM" + formatter.format(NewSal));
}
else if(Salary > 25000){
Comm = (Salary * p4);
NewSal = Salary + Comm;
System.out.print("Your Commition is RM" + formatter.format(Comm));
System.out.println(" and your New Salary is RM" + formatter.format(NewSal));
}
else{
System.out.println("Input invalid. Renter Salary");
}
}
}
You have written While instead of while.
do {
...
} While (Salary < 0);
correct would be:
do {
...
} while (Salary < 0);
Hope this solves your problem.
Your do-while loop has an invalid syntax. Firstly, while is lowercase, thus While is incorrect. Moreover, you are missing a semicolon.
do {
System.out.print("Enter your Salary: ");
Salary = input.nextInt();
} while (Salary < 0);
On a side note, in Java variables usually start with lowercase letters. It is not a strict rule, but a convention that it is prudent to conform to.

Java Payroll ACME Project, Compiling problems

I have to create a program which has to include three or more classes including my Main class which will run the class simultaneously. Right now, I have a class called EmployeeRecord, which will create arrays for the employees information (employee full name, tax ID, employee ID, and their wage), and another class called Payroll, which is the class I am having the most trouble. In my if and else if statements, I am getting an error when trying to compile stating "incompatible types: double cannot be converted to java.util.ArrayList." I cannot quite understand or find a fix to solve the problem. I have posted my two classes for you. Thanks.
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Date;
/**
*
* #Lab Three
* #author Joseph Malachosky
* #version 9/14/2015
*/
public class Payroll
{
//ArrayLists that will use methods from EmployeeRecords.
ArrayList<String> employeeNames2;
ArrayList<Double> employeeWages2;
ArrayList<Integer> emID = new ArrayList<Integer>();
ArrayList<Double> hours = new ArrayList<Double>();
ArrayList<Double> totalPay = new ArrayList<Double>();
//Creating the hours and wages variables.
private double hoursWorked = 0.0;
private double hoursWorked2 = 0.0;
private int weeks = 0;
private String employeeID = "%03d";
private int quit = 1000;
private int i = 0;
Scanner input = new Scanner(System.in);
public void setEmployeePayroll()
{
// Constructs a new EmployeeRecord.
EmployeeRecord e = new EmployeeRecord();
e.setEmployeeInfo();
employeeNames2 = e.getEmployeeNamesArrayList();
employeeWages2 = e.getWageArrayList();
// Local variables used in setEmployeePayroll.
double totalPay2 = 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(quit != 0)
{
quit = input.nextInt();
if(quit == 0)
{
break;
}
weeks = input.nextInt();
if(weeks == 1)
{
hoursWorked = input.nextDouble();
}
else if(weeks == 2)
{
hoursWorked2 = input.nextDouble();
}
/*
* I am checking to see if the employee is going to be paid for overtime and also calculating the pay for both weeks.
* 1) My first if statement indicates whether or not the employee worked over 40 in week one and week two.
* 2) My first else if statement indicates whether the employee works more than 40 hours in week two but not week one.
* 3) My second else if statement indicates whether the employee works more than 40 hours in week one but not in week two.
* 3) My third else if statement finally indicates that the employee worked over 40 hours in both week one and two.
*/
if(hoursWorked > 0 && hoursWorked <= 40 && hoursWorked2 > 0 && hoursWorked2 <= 40)
{
totalHours = hoursWorked + hoursWorked2;
hours.add(totalHours);
totalPay = totalHours * (employeeWages2.get(i - 1));
totalPay.add(totalPay2);
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 * (employeeWages.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 * (employeeWages.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 * (employeeWages.get(i - 1)) + (1.5 * (overTime + overTime2));
tPay.add(totalPay);
hoursWorked = 0.0;
hoursWorked2 = 0.0;
}
i = terminate;
}
System.out.println();
System.out.println("Employee Number | Employee Name | Hours Worked | Total Pay");
for(int i = 1; i <= e.getEmployeeNamesArrayList().size(); i++)
{
System.out.println(String.format(employeeID, i) + " | " + emID.get(i - 1) + " | " + hours.get(i - 1) + " | " + totalPay.get(i - 1));
}
}
}
import java.util.Scanner;
import java.util.ArrayList;
/**
* Creating the objects and getMethods for each item that is stored in EmployeeRecord.
* #Lab Three
* #author Joseph Malachosky
* #version 9/14/2015
*/
public class EmployeeRecord
{
/*
* Creating the array and instance variables for EmployeeRecord consisting
* of TaxID numbers, Employee Names, Wages, Employee ID numbers and hours worked.
*/
ArrayList<String> employeeNames = new ArrayList<String>();
ArrayList<String> taxIDList = new ArrayList<String>();
ArrayList<Double> employeeWages = new ArrayList<Double>();
Scanner input = new Scanner(System.in);
private String employeeID = "%03d";
private String employeeFullName = " ";
private String taxID = " ";
private double wage = 0.0;
//Adding employees.
public void setEmployeeInfo()
{
System.out.println("Please enter the full names of each ACME employee, their employee tax ID, and their employee wage rate. Press Q when you are done entering employee information.");
while(employeeFullName != "Q")
{
employeeFullName = input.next();
if(employeeFullName == "Q")
{
break;
}
taxID = input.next();
wage = input.nextDouble();
employeeNames.add(employeeFullName);
taxIDList.add(taxID);
employeeWages.add(wage);
System.out.println("Employee ID | Employee Name | Tax ID | Wage");
for(int i = 1; i <= employeeNames.size(); i++)
{
System.out.printf(String.format(employeeID, i) + " | " + employeeNames.get(i - 1) + " | " + taxIDList.get(i - 1) + " | " + "%1.2f",employeeWages.get(i - 1));
System.out.println();
}
}
}
/**
* Creating a method that returns the employee ArrayList employeeName.
*/
public ArrayList<String> getEmployeeNamesArrayList()
{
return employeeNames;
}
/**
* Creating a method that returns the employee's Tax ID ArrayList taxIDList.
*/
public ArrayList<String> getTaxIdsArrayList()
{
return taxIDList;
}
/**
* Creating a method that returns the wages ArrayList
*/
public ArrayList<Double> getWageArrayList()
{
return employeeWages;
}
}
You have
ArrayList<Double> totalPay = new ArrayList<Double>();
and then:
totalPay = totalHours * (employeeWages2.get(i - 1));
Does your compiler not tell you the line number?
i've found your mistake.
change:
totalPay = totalHours * (employeeWages2.get(i - 1));
to:
totalPay2 = totalHours * (employeeWages2.get(i - 1));

Is there a way to use words instead of numbers as outputs?

I want to use words instead of typing numbers. It's for someone who wants to order a food on a menu.
This is my output:
2
Good Salad $7.00
3
Soda $2.00
5
I just want to type Good Salad and go to the next line and so on. How do i fix this?
This is the rest of the code:
import java.util.Scanner;
import java.text.DecimalFormat;
public class Project1 {
public static void main(String[] args) {
int choice = 0;
boolean doneOrdering = false;
boolean yes = false;
String order, A, B;
Scanner Keyboard = new Scanner(System.in);
DecimalFormat moneyFormat = new DecimalFormat("$#,###.00");
double num, GoodBurger = 0, GoodSalad = 0, Soda = 0, KidsMeal = 0;
double GoodBurgers = 7.75;
double GoodSalads = 7.00;
double Sodas = 2.00;
double KidsMeals = 3.00;
double tax;
double subtotal = 0, total;
int C = 0;
double tip = 0.010;
final double salestax = 0.081;
System.out.println("Welcome to Good Burger!");
System.out.println("=======================");
System.out
.println("Place your orders and type 'Finish' when you are done");
System.out
.println("--------------------------------------------------------");
System.out.println("1. GoodBurger $8.00");
System.out.println("2. GoodSalad $ 7.00");
System.out.println("3. Soda $2.00");
System.out.println("4. KidsMeal $3.00");
System.out.println("Type '5' if you want to tip. \n");
System.out.println("What would you like?");
while (!doneOrdering) {
choice = Keyboard.nextInt();
if (choice == 1) {
System.out.println("GoodBurger $8.00");
subtotal = subtotal + 8.00;
} else if (choice == 2) {
System.out.println("Good Salad $7.00");
subtotal = subtotal += 7.00;
} else if (choice == 3) {
System.out.println("Soda $2.00");
subtotal = subtotal + 2.00;
} else if (choice == 4) {
System.out.println("KidsMeal $3.00");
subtotal = subtotal + 3.00;
} else if (choice == 5) {
doneOrdering = true;
System.out.println("Do you want to tip?");
A = Keyboard.next();
if (A.equalsIgnoreCase("yes")) {
System.out.print("What percentage would you like to tip? ");
C = Keyboard.nextInt();
double tiptotal = C * tip * subtotal;
double taxtotal = subtotal * salestax;
System.out.println("SubTotal $" + subtotal);
System.out.println("Tax " + salestax);
System.out.println("Tip $" + tiptotal);
System.out.println("-------------------------");
System.out.println(subtotal + tiptotal + taxtotal);
}
if (A.equalsIgnoreCase("no")) {
double tiptotal = C * tip * subtotal;
double taxtotal = subtotal * salestax;
System.out.println("SubTotal $" + subtotal);
System.out.println("Tax " + salestax);
System.out.println(subtotal + tiptotal + taxtotal);
}
} else
System.out.println("Invalid");
}
}
}
This example uses an HashMap to record prices:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Project1 {
private static String userMessage() {
StringBuffer buffer = new StringBuffer();
String lineSeparator = System.getProperty("line.separator");
buffer.append("Welcome to Good Burger!");
buffer.append(lineSeparator);
buffer.append("=======================");
buffer.append(lineSeparator);
buffer.append("Place your orders and type 'Finish' when you are done");
buffer.append(lineSeparator);
buffer.append("--------------------------------------------------------");
buffer.append(lineSeparator);
buffer.append("1. GoodBurger $8.00");
buffer.append(lineSeparator);
buffer.append("2. GoodSalad $ 7.00");
buffer.append(lineSeparator);
buffer.append("3. Soda $2.00");
buffer.append(lineSeparator);
buffer.append("4. KidsMeal $3.00");
buffer.append(lineSeparator);
buffer.append("Type '5' if you want to tip. \n");
buffer.append(lineSeparator);
buffer.append("What would you like?");
buffer.append(lineSeparator);
return buffer.toString();
}
private static Map<String, Double> getPrices() {
Map<String, Double> prices = new HashMap<String, Double>();
prices.put("GoodBurgers", 7.75);
prices.put("GoodSalads", 7.00);
prices.put("Sodas", 2.00);
prices.put("KidsMeals", 3.00);
return prices;
}
public static void main(String[] args) {
String choice;
boolean doneOrdering = false;
String tipConfirmation;
Scanner Keyboard = new Scanner(System.in);
double subtotal = 0;
int C = 0;
double tip = 0.010;
final double salestax = 0.081;
String userMessage = userMessage();
System.out.println(userMessage);
Map<String, Double> prices = getPrices();
while (!doneOrdering) {
choice = Keyboard.next();
if (prices.containsKey(choice)) {
double price = prices.get(choice);
System.out.println(choice + " " + price);
subtotal = subtotal + price;
} else if (choice == "Tip") {
doneOrdering = true;
System.out.println("Do you want to tip?");
tipConfirmation = Keyboard.next();
if (tipConfirmation.equalsIgnoreCase("yes")) {
System.out.print("What percentage would you like to tip? ");
C = Keyboard.nextInt();
double tiptotal = C * tip * subtotal;
double taxtotal = subtotal * salestax;
System.out.println("SubTotal $" + subtotal);
System.out.println("Tax " + salestax);
System.out.println("Tip $" + tiptotal);
System.out.println("-------------------------");
System.out.println(subtotal + tiptotal + taxtotal);
}
if (tipConfirmation.equalsIgnoreCase("no")) {
double tiptotal = C * tip * subtotal;
double taxtotal = subtotal * salestax;
System.out.println("SubTotal $" + subtotal);
System.out.println("Tax " + salestax);
System.out.println(subtotal + tiptotal + taxtotal);
}
} else
System.out.println("Invalid");
}
}
}
So one technique is to store the strings you want to use in a HashMap, then look them up to get the rest of the info that you need. For example:
static String[] foods = { "Good Burger", "Good Salad", "Kid's Meal", "Drink" };
static double[] costs = { 8.0, 7.0, 3.0, 0.75 };
HashMap<String, FoodItem> itemLookup = new HashMap<>();
{
for( int i = 0; i < foods.length; i++ ) {
itemLookup.put( foods[i], new FoodItem( foods[i], costs[i] ) );
}
}
That puts all your strings into a HashMap, plus a new object FoodItem which stores any additional relevant information you'd need to process the food item.
When the user enters a food name, just look it up in the HashMap.
FoodItem item = itemLookup.get( s.trim() );
if( item == null ) System.out.println("I couldn't find a "+ s );
Here I added a trim() to get rid of any white space, which would cause the string to be not found since HashMap only return exact matches.
That's the main idea. The following is a bit rough, but works (I tried it once) and gives you an idea how to put something together.
class FoodMenu {
class FoodItem {
public FoodItem( String name, double cost )
{
this.name = name;
this.cost = cost;
}
String name;
double cost;
#Override
public String toString()
{
return "FoodItem{" + "name=" + name + ", cost=" + cost + '}';
}
}
static String[] foods = { "Good Burger", "Good Salad", "Kid's Meal", "Drink" };
static double[] costs = { 8.0, 7.0, 3.0, 0.75 };
HashMap<String, FoodItem> itemLookup = new HashMap<>();
{
for( int i = 0; i < foods.length; i++ ) {
itemLookup.put( foods[i], new FoodItem( foods[i], costs[i] ) );
}
}
List<FoodItem> process( Reader input ) throws IOException {
BufferedReader bin = new BufferedReader( input );
ArrayList<FoodItem> order = new ArrayList<>();
for( String s; (s = bin.readLine()) != null && s.length() > 0; ) {
FoodItem item = itemLookup.get( s.trim() );
if( item == null ) System.out.println("I couldn't find a "+ s );
else order.add(item);
}
return order;
}
public static void main(String[] args) throws IOException {
System.out.println("Enter a food item name to order it.");
System.out.println("Items available: "+ Arrays.toString( foods ) );
System.out.println("Press enter on a blank line to finish");
List<FoodItem> order = new FoodMenu().process( new InputStreamReader( System.in ));
System.out.println("You ordered: "+order );
}
}

Categories

Resources