Calculating employee pay with methods - java

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.

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

Incorrect Math In Program, not sure why?

I am writing a simple program for class. I am not sure why the math is not showing correctly? When I ask for a tax and input 0.08 it is not computing to the right number. For example entering 1234.55 as the retail amount gives a transaction amount of 1266.6483 instead of the correct amount which should be 1333.31. Any help would be appreciated... I'll post the code below
package Project03Driver;
import java.io.*;
public class Project03Driver
{
public static void main(String args[]) throws IOException
{
Project03 app;
app = new Project03();
app.appMain();
}
}
class Project03
{
BufferedReader stdin;
int tNum, tCount, smallTnum;
double tax, rA, tA, raTot, disTot, taTot, taAvg, smallTa;
boolean disc;
String store, date, dFlag, inString;
public void appMain() throws IOException
{
rptInit();
displayHeader();
getStore();
while(tNum != 0)
{
salesData();
}
calcAvg();
rptOut();
}
void rptInit()
{
tNum = 1;
tCount = smallTnum = 0;
raTot = disTot = taTot = taAvg = 0;
smallTa = 10000;
stdin = new BufferedReader (new InputStreamReader(System.in));
}
void displayHeader()
{
System.out.println("Project #03 Solution");
System.out.println("Written by Jordan Hawkes");
}
void getStore() throws IOException
{
System.out.println("Enter Store: ");
store = stdin.readLine();
System.out.println("Enter Date: ");
date = stdin.readLine();
System.out.println("Enter Tax as Decimal (ex. .05): ");
tax = Double.parseDouble(stdin.readLine());
}
void salesData() throws IOException
{
getTransNum();
if (tNum != 0)
{
inputRa();
calcSalesData();
outputSalesData();
}
}
void getTransNum() throws IOException
{
System.out.println("Enter Transaction Number: ");
tNum = Integer.parseInt(stdin.readLine());
}
void inputRa() throws IOException
{
System.out.println("Enter Retail Amount: ");
rA = Double.parseDouble(stdin.readLine());
}
void calcSalesData()
{
tCount = tCount + 1;
raTot = raTot + rA;
if (tA > 1500)
{
disc = true;
dFlag = "Discounted";
}
else
{
disc = false;
dFlag = "No";
}
transAmt();
discTot();
taTot = taTot +tA;
smallTrans();
}
void transAmt()
{
if (disc = true)
{
tA = (rA * 0.95) + ((rA * 0.95) * tax);
}
else
{
tA = (rA * tax) + rA;
}
}
void discTot()
{
if (disc = true)
{
disTot = disTot + (tA - rA);
}
else
{
disTot = disTot;
}
}
void smallTrans()
{
if (tA < smallTa)
{
smallTa = tA;
smallTnum = tNum;
}
}
void outputSalesData()
{
System.out.println("");
System.out.println("--------------------------------------------");
System.out.println("Transaction Number: " + tNum);
System.out.println("Retail Amount: " + rA);
System.out.println("Discount Flag: " + dFlag);
System.out.println("Transaction Amount: " + tA);
System.out.println("--------------------------------------------");
System.out.println("");
}
void calcAvg()
{
taAvg = taTot / tCount;
}
void rptOut()
{
System.out.println("");
System.out.println("--------------------------------------------");
System.out.println("Store: " + store);
System.out.println("Date: " + date);
System.out.println("Tax Rate: " + tax);
System.out.println("--------------------------------------------");
System.out.println("Retail Amount Total: " + raTot);
System.out.println("Discount Total: " + disTot);
System.out.println("Transaction Amount Total: " + taTot);
System.out.println("Average Transaction Amount: " + taAvg);
System.out.println("Smallest Transaction Amount: " + smallTa);
System.out.println("Smallest Transaction Number: " + smallTnum);
System.out.println("--------------------------------------------");
}
}
if (disc = true)
should be
if (disc == true)
I think you should delete the question, because that is a typo. According to https://stackoverflow.com/help/on-topic

Addition in Java program equals different value

I'm having a problem with this Java code. It's a questionnaire that should calculate your grade. It all goes and runs well until the very last part where it says "current score" that whole equation should equal 33.16 but instead it equals 24.
I changed some values, did some research but I haven't found what I'm looking for.
import java.util.Scanner;
public class GradeCalculator {
public static void main(String[] args) {
System.out.println("Grading Scale:");
System.out.println("A\t 90 - 100");
System.out.println("B\t 80 - 89");
System.out.println("C\t 70 - 79");
System.out.println("D\t 60 - 69");
System.out.println("F\t below 60");
System.out.println("What letter grade do you want to achieve for the course?");
String desiredGrade;
Scanner keyboard = new Scanner(System.in);
desiredGrade = keyboard.next();
if (desiredGrade.equalsIgnoreCase("A") || desiredGrade.equalsIgnoreCase("B")
|| desiredGrade.equalsIgnoreCase("C") || desiredGrade.equalsIgnoreCase("D")
|| desiredGrade.equalsIgnoreCase("F")) {// is this necessary? vv
System.out.println("Enter Percentage Weights");
}
else {
System.out.println("Input error.");
System.exit(0);
}
int exam1, exam2, finalExam, labs, projects, attendance, quizzes;
System.out.println("Exam 1:\t");
exam1 = keyboard.nextInt();
System.out.println("Exam 2:\t");
exam2 = keyboard.nextInt();
System.out.println("Final Exam:\t");
finalExam = keyboard.nextInt();
System.out.println("Labs:\t");
labs = keyboard.nextInt();
System.out.println("Projects:\t");
projects = keyboard.nextInt();
System.out.println("Attendance:\t");
attendance = keyboard.nextInt();
System.out.println("Quizzes:\t");
quizzes = keyboard.nextInt();
// so the semicolon isn't needed after the if statement?
if (exam1 + exam2 + finalExam + labs + projects + attendance + quizzes != 100) {
System.out.println("Weights don't add up to 100, program exiting");
System.exit(0);
}
System.out.println("Enter your scores out of a 100:");
System.out.println("Do you know your Exam 1 score?");
String answer;
int exam1score = 0, exam2score = 0, finalExamScore = 0, labAverage = 0, projectAverage = 0, quizAverage = 0, attendanceAverage = 0;
double currentScore = 0;
answer = keyboard.next();
// ask about this
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
// why can't i put int here?
System.out.println("Score received on exam 1:");
exam1score = keyboard.nextInt();
System.out.println("Do you know your Exam 2 score?");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Score received on exam 2:");
exam2score = keyboard.nextInt();
System.out.println("Do you know your Final Exam score?");
answer = keyboard.next();
}
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Score received on final exam");
finalExamScore = keyboard.nextInt();
}
}
System.out.println("Do you know your lab average?");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Average Lab Grade:");
labAverage = keyboard.nextInt();
}
System.out.println("Do you know your project average?");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Average Project Grade:");
projectAverage = keyboard.nextInt();
}
System.out.println("Do you know your quiz average?");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Average Quiz Grade:");
quizAverage = keyboard.nextInt();
}
System.out.println("Do you know your attendance average?");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Average Attendance Grade:");
attendanceAverage = keyboard.nextInt();
}
currentScore = ((double)exam1score*exam1 + exam2score*exam2 +finalExam*finalExamScore + labs*labAverage + projects*projectAverage + attendance*attendanceAverage + quizzes*quizAverage)/((double)exam1+exam2+finalExam+labs+projects+attendance+quizzes);
System.out.println("Current Grade Score:\t " + currentScore);
String grade;
if (currentScore >= 90)
grade = "A";
else if (currentScore >= 80)
grade = "B";
else if (currentScore >= 70)
grade = "C";
else if (currentScore >= 60)
grade = "D";
else
grade = "F";
}
}
The following only converts the exam1score*exam1 value to double, not the entire expression.
(double) exam1score*exam1 + exam2score*exam2 + finalExam*finalExamScore + ....
So, you should do something like this.
int nominator = exam1score*exam1 + exam2score*exam2 + finalExam*finalExamScore
+ labs*labAverage + projects*projectAverage
+ attendance*attendanceAverage + quizzes*quizAverage;
int denominator = exam1 + exam2 + finalExam + labs + projects + attendance + quizzes;
currentScore = (double) nominator / denominator;
OR
int nominator = exam1score*exam1 + exam2score*exam2 + finalExam*finalExamScore
+ labs*labAverage + projects*projectAverage
+ attendance*attendanceAverage + quizzes*quizAverage);
int denominator = exam1 + exam2 + finalExam + labs + projects + attendance + quizzes;
currentScore = (nominator * 1.0) / denominator;
(double)exam1score*exam1 + exam2score*exam2 +finalExam*finalExamScore + labs*labAverage + projects*projectAverage + attendance*attendanceAverage + quizzes*quizAverage
only converts the first one to double and leaves the rest as int.

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.

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