Java program....new to programming - java

this is my first question here, so here it goes, I have tried this for ages with no luck, I am new to Java (studying it) and I have an assignment and I cant get this to work (only the first part works)...thanks in advanced for any help you can give me! :)
**Write a program to read in a non-specified number of Employee Salaries from the user. After each Employee Salary is entered the program should then calculate the Bonus for each employee. The bonus is to be calculated as a percentage of the Salary, according to the table shown below:
Salary Bonus Rate
Less than €10,000 5%
Between €10,000 and less than €20,000 10%
Between €20,000 and less than €30,000 15%
€30,000 or more 20%
The Program should output the Bonus Rate, Bonus Amount, and Total Salary for each Employee after the salary is entered.
When the user has entered the details for all employees, the program should then output the following:
Overall Total Bonuses paid
Overall Total Salaries paid (including bonuses)
Average Bonus
Your program should let the user indicate that they have finished entering results.
Add extra checks to your program so that negative figures are rejected by the program along with a suitable error message.
Test your program thoroughly, so that it works under all possible conditions.
Input/Output from the program should be attractively displayed on the screen.
import java.util.Scanner;
class Salary
{
public static void main (String args [])
{
Scanner myInput = new Scanner (System.in);
double salary =0, bonusRate =0, bonusAmount=0, salaryTotal=0, totalBonus=0, averageBonus=0, totalSalaries=0;
int salaryCounter=0;
char response;
do
{
System.out.println("Press a to enter a salary or press 'q' to quit");
response=myInput.next().charAt(0);
switch(response)
{
case 'a':
do
{
System.out.println("Enter employee salary or press q to quit");
salary = myInput.nextDouble();
if (salary <=0)
{
System.out.println("Invalid entry please enter Salary again ");
}
else if (salary >0 && salary <=10000)
{
System.out.println("*************************************************************");
System.out.println("The bonus rate is 5%");
bonusRate = salary * .05;
System.out.println("The bonus is " + bonusRate);
salaryTotal= salary + bonusRate;
System.out.println("The Total salary " + salaryTotal);
salaryCounter=salaryCounter+1;
System.out.println("*************************************************************");
}
else if (salary >10000 && salary <=20000)
{
System.out.println("*************************************************************");
System.out.println("The bonus rate is 10%");
bonusRate = salary * .10;
System.out.println("The bonus is " + bonusRate);
salaryTotal= salary + bonusRate;
System.out.println("The Total salary " + salaryTotal);
salaryCounter=salaryCounter+1;
System.out.println("*************************************************************");
}
else if (salary >20000 && salary <=30000)
{
System.out.println("*************************************************************");
System.out.println("The bonus rate is 15%");
bonusRate = salary * .15;
System.out.println("The bonus is " + bonusRate);
salaryTotal= salary + bonusRate;
System.out.println("The Total salary " + salaryTotal);
salaryCounter=salaryCounter+1;
System.out.println("*************************************************************");
}
else if (salary >30000)
{
System.out.println("*************************************************************");
System.out.println("The bonus rate is 20%");
bonusRate = salary * .20;
System.out.println("The bonus is " + bonusRate);
salaryTotal= salary + bonusRate;
System.out.println("The Total salary " + salaryTotal);
salaryCounter=salaryCounter+1;
System.out.println("*************************************************************");
}
//else
//{ //do i need to get rid of this?
// System.out.println("");
//}
}while(salary <=0);{
break;
}case 'q':
salaryCounter = salaryCounter+1;
bonusAmount= salary*bonusRate;
salaryTotal=salary+bonusAmount;
totalBonus=totalBonus+bonusAmount;
totalSalaries=totalSalaries+salaryTotal;
averageBonus=totalBonus*salaryCounter;
System.out.printf("The Total Salaries paid including Bonus is %.2f " , totalSalaries);
System.out.println("Euro");
System.out.printf("The Total of Bonuses paid is %.2f ", totalBonus);
System.out.println("Euro");
System.out.printf("The Total of Average Bonuses paid is %.2f ", averageBonus);
System.out.println("Euro");
break;
}//end do
//end switch
}while (response != 'q');{
//do while loop to repeat until 'q' is entered.
} //end do while loop
}//end main
}//end class

You can create two different files for your requirements: one pojo class containing the attributes of the employee and second main app where the user interacts with the program.
Salary.java
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
public class Salary {
private static int count = 0;
private int empId;
private double salary;
private int bonusRate;
private double bonusAmount;
private double totalSalary;
//Getters and Setters
public int getEmpId() {
return empId;
}
public double getTotalSalary() {
return totalSalary;
}
public void setTotalSalary(double totalSalary) {
this.totalSalary = totalSalary;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public int getBonusRate() {
return bonusRate;
}
public void setBonusRate(int bonusRate) {
this.bonusRate = bonusRate;
}
public double getBonusAmount() {
return bonusAmount;
}
public void setBonusAmount(double bonusAmount) {
this.bonusAmount = bonusAmount;
}
//Constructors
public Salary(int empId, double salary, int bonusRate, double bonusAmount,
double totalSalary) {
super();
this.empId = empId;
this.salary = salary;
this.bonusRate = bonusRate;
this.bonusAmount = bonusAmount;
this.totalSalary = totalSalary;
}
public Salary() {
super();
count = count + 1;
this.empId = count;
}
//toString
#Override
public String toString() {
return "Salary [empId=" + empId + ", salary=" + salary + ", bonusRate="
+ bonusRate + ", bonusAmount=" + bonusAmount + ", totalSalary="
+ totalSalary + "]";
}
//calculation function
public void calculateBonus(){
double bonus;
if(this.getSalary()<10000){
this.setBonusRate(5);
bonus = this.getSalary() + 0.05*(this.getSalary());
}else if(this.getSalary()<20000){
this.setBonusRate(10);
bonus = this.getSalary() + 0.10*(this.getSalary());
}else if(this.getSalary()<30000){
this.setBonusRate(15);
bonus = this.getSalary() + 0.15*(this.getSalary());
}else{
this.setBonusRate(20);
bonus = this.getSalary() + 0.20*(this.getSalary());
}
this.setBonusAmount(bonus);
this.setTotalSalary(this.getSalary() + bonus);
}
}
MainApp.java
import java.util.ArrayList;
import java.util.Scanner;
public class MainApp {
public static void main(String[] args) {
ArrayList<Salary> salaries = new ArrayList<Salary>();
Scanner sc = new Scanner(System.in);
String op = "y";
do {
Salary salary = new Salary();
System.out.println("Please Enter Salary for User "
+ salary.getEmpId() + " :");
salary.setSalary(sc.nextDouble());
salary.calculateBonus();
System.out.println(salary);
salaries.add(salary);
System.out.println("Do you want to enter more salaries: ");
op = sc.next();
} while (op.equals("y"));
double totalSalaries = 0;
double totalBonus = 0;
double averageBonus = 0;
int numberOfSalaries = 0;
for (Salary salary : salaries) {
System.out.println("Empid: " + salary.getEmpId() + " Salary: "
+ salary.getSalary() + " Bonus Rate: "
+ salary.getBonusRate() + " Bonus Amount: "
+ salary.getBonusAmount() + " Total Salary: "
+ salary.getTotalSalary());
totalSalaries = totalSalaries + salary.getTotalSalary();
totalBonus = totalBonus + salary.getBonusAmount();
numberOfSalaries = numberOfSalaries + 1;
}
averageBonus = totalBonus / numberOfSalaries;
System.out.println("Total Salaries for all employees: " + totalSalaries
+ " Total Bonuses: " + totalBonus
+ " Average Bonuses for all employees: " + averageBonus);
}
}
The code shall suffice your requirements.

Related

Unable to get total amount payable [duplicate]

This question already has answers here:
Unable to get total amount
(2 answers)
Closed 4 years ago.
I have designed a program which will rerun when the user enters "y" when asked if they wish to continue. The problem I am having is once the user enters "n" the program is supposed to display the total amount payable from all ticket options purchased. I have spent a couple of weeks stuck on this problem and am unsure of what to do next. I have only included the bottom part of my code. I have also included a photo to show my problem when the program is run.
here is my code:
package cse1pgx_a2;
import java.util.Scanner;
public class CSE1PGX_A2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int option, quantity, confirm;
float childTotal = 0;
float adultTotal = 0;
float seniorTotal = 0;
float finalTotal = 0;
final double childCost = 18;
final double adultCost = 36;
final double seniorCost = 32.50;
boolean continueLoop = true;
char resume;
Scanner input = new Scanner(System.in);
while (continueLoop) {
System.out.println("\t"+ "##### Welcome to Zoos Victoria #####");
System.out.println("\t" + "\t" + "MAIN MENU" + "\n");
System.out.println("\t" + "Zoo has the following ticketing options" + "\n");
System.out.println("\t" + "1 = Child (4-6 yrs)");
System.out.println("\t" + "2 = Adult (16+ yrs)");
System.out.println("\t" + "3 = Senior (60+ yrs)" + "\n");
System.out.println("Enter your option:" );
option=input.nextInt();
switch (option) {
case 1:
System.out.println("Enter total No of tickets for Child:" );
quantity=input.nextInt();
System.out.println("You are purchasing " + quantity + " child tickets at " + childCost + " each!");
System.out.println("Press 1 to confirm");
confirm=input.nextInt();
break;
case 2:
System.out.println("Enter total No of tickets for Adult:" );
quantity=input.nextInt();
System.out.println("You are purchasing " + quantity + " adult tickets at " + adultCost + " each!");
System.out.println("Press 1 to confirm");
confirm=input.nextInt();
break;
default:
System.out.println("Enter total No of tickets for Senior:" );
quantity=input.nextInt();
System.out.println("You are purchasing " + quantity + " senior tickets at " + seniorCost + " each!");
System.out.println("Press 1 to confirm");
confirm=input.nextInt();
break;
}
if (confirm !=1) {
System.out.println("Incorrect key!");
}
OUTER:
while (confirm == 1) {
switch (option) {
case 1:
childTotal=(int) ((double) quantity*childCost) ;
System.out.println("Total amount for child tickets: $" + childTotal);
break OUTER;
case 2:
adultTotal=(int) ((double) quantity*adultCost) ;
System.out.println("Total amount for adult tickets $" + adultTotal);
break OUTER;
default:
seniorTotal=(int) ((double) quantity*seniorCost);
System.out.println("Total amount for senior tickets $" + seniorTotal);
break OUTER;
}
}
System.out.println("Do you wish to continue? (Y/N) ");
resume = input.next().charAt(0);
if (resume == 'y' || resume == 'Y') {
} else {
continueLoop = false;
switch (option) {
case 1:
finalTotal=(float) ((double) childTotal+adultTotal+seniorTotal) ;
System.out.println("Total amount payable: $ " + finalTotal);
break;
default:
System.out.println("Error");
}
}
}
}
}
I have fixed issues and also updated code for better performance.
package test;
import java.util.Scanner;
public class CSE1PGX_A2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
final float childCost = 18;
final float adultCost = 36;
final float seniorCost = 32.50F;
boolean continueLoop = true;
Scanner input = new Scanner(System.in);
float childTotal = 0;
float adultTotal = 0;
float seniorTotal = 0;
while (continueLoop) {
int option, confirm=0;
System.out.println("\t ##### Welcome to Zoos Victoria #####");
System.out.println("\t \t MAIN MENU \n");
System.out.println("\t Zoo has the following ticketing options \n");
System.out.println("\t 1 = Child (4-6 yrs)");
System.out.println("\t 2 = Adult (16+ yrs)");
System.out.println("\t 3 = Senior (60+ yrs) \n");
System.out.println("Enter your option:");
option = input.nextInt();
switch (option) {
case 1: {
System.out.println("Enter total No of tickets for Child:");
int quantity = input.nextInt();
childTotal = quantity * childCost;
System.out.println("You are purchasing " + quantity + " child tickets at " + childCost + " each!");
System.out.println("Press 1 to confirm");
confirm = input.nextInt();
if (confirm == 1) {
System.out.println("Total amount for child tickets: $" + childTotal);
}
break;
}
case 2: {
System.out.println("Enter total No of tickets for Adult:");
int quantity = input.nextInt();
adultTotal = quantity * adultCost ;
System.out.println("You are purchasing " + quantity + " adult tickets at " + adultCost + " each!");
System.out.println("Press 1 to confirm");
confirm = input.nextInt();
if (confirm == 1) {
System.out.println("Total amount for adult tickets $" + adultTotal);
}
break;
}
case 3: {
System.out.println("Enter total No of tickets for Senior:");
int quantity = input.nextInt();
seniorTotal = quantity * seniorCost ;
System.out.println("You are purchasing " + quantity + " senior tickets at " + seniorCost + " each!");
System.out.println("Press 1 to confirm");
confirm = input.nextInt();
if (confirm == 1) {
System.out.println("Total amount for senior tickets $" + seniorTotal);
}
break;
}
}
if (confirm != 1) {
System.out.println("Incorrect key!");
}
System.out.println("Do you wish to continue? (Y/N) ");
char resume = input.next().charAt(0);
if (resume != 'y' && resume != 'Y') {
continueLoop = false;
System.out.println("Total amount for child tickets: $" + childTotal);
System.out.println("Total amount for senior tickets $" + seniorTotal);
System.out.println("Total amount for adult tickets $" + adultTotal);
float finalTotal = childTotal + adultTotal + seniorTotal ;
System.out.println("Total amount payable: $ " + finalTotal);
}
}
}
}
Try this code. I hope it helps.
public static void main(String[] args) {
int option, quantity, confirm; //minor change
float childTotal = 0;
float adultTotal = 0;
float seniorTotal = 0;
float finalTotal = 0; //minor change
final double childCost = 18;
final double adultCost = 36;
final double seniorCost = 32.50;
boolean continueLoop = true;
char resume;
System.out.println("Do you wish to continue? (Y/N) ");
resume = input.next().charAt(0);
if (resume == 'y' || resume == 'Y') {
}else{
continueLoop = false;
switch (option) {
case 1:
finalTotal+=(double) quantity*childTotal ; //minor change
System.out.println("Total amount payable: $" + childTotal);
break;
case 2:
finalTotal+=(double) quantity*adultTotal ; //minor change
System.out.println("Total amount payable $" + adultTotal);
break;
default:
finalTotal+=(double) quantity*seniorTotal; //minor change
System.out.println("Total amount payable $" + seniorTotal);
break;
}
}
}
}
}
I wished to play and did not fully understand the problem...so i developed from scratch the application. Suryakant was faster so please accept his answer (if it solves your problem). I simply post this here since i worked on it :-)
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean continueLoop = true;
Map<TicketType, Integer> purchases=new HashMap<>();
do {
TicketType type = printMenu(scan);
System.out.println("Enter number of tickets for " + type.label);
int quantity = scan.nextInt();
System.out.println("You are purchasing "+quantity + " "+ type.label+ " ticket at "+type.cost+" each. " +
"Press 1 to confirm?");
int confirm= scan.nextInt();
if (confirm!=1) continue;
if (purchases.containsKey(type)){
purchases.put(type,purchases.get(type)+quantity);
System.out.println("You now have " +purchases.get(type) +" "+type.label +" tickets in total");
}else {
purchases.put(type,quantity);
}
System.out.println("You have added " +quantity +" "+type.label +" tickets in your basket.");
System.out.println("Do you wish to continue (Y|N)?");
String resume=scan.next();
if (resume.startsWith("Y") || resume.startsWith("y")){
continueLoop=true;
}else {
continueLoop=false;
}
}while (continueLoop);
System.out.println("Purchases");
long total=0;
for (Map.Entry<TicketType, Integer> ticketTypeIntegerEntry : purchases.entrySet()) {
System.out.println(ticketTypeIntegerEntry.getKey().label+"("+ticketTypeIntegerEntry.getValue()+")");
total+=ticketTypeIntegerEntry.getKey().cost*ticketTypeIntegerEntry.getValue();
}
System.out.println("Total payable ammount: "+total);
}
private static TicketType printMenu(Scanner scan) {
System.out.println("Welcome");
TicketType type;
int k = -1;
do {
for (TicketType ticketType : TicketType.values()) {
System.out.println(ticketType.id + ". for " + ticketType.label);
}
System.out.println("Enter your option");
k = scan.nextInt();
} while ((type=TicketType.valuefromId(k))==null);
return type;
}
private enum TicketType {
CHILD(1, "Child", 18D),
ADULT(2, "Adult", 36D),
SENIOR(3, "Senior", 18.5D);
int id;
String label;
double cost;
private static Map<Integer,TicketType> map=new HashMap<Integer,TicketType>();
static {
for (TicketType ticketType : TicketType.values()) {
map.put(ticketType.id,ticketType);
}
}
TicketType(int id, String label, double cost) {
this.id = id;
this.label = label;
this.cost=cost;
}
public static TicketType valuefromId(int id){
return map.get(id);
}
}
}
improvements are in reading.. i would check first if what i read is character or not..

printf is giving me the wrong output

I have
System.out.printf("$%.2f\t $%.2f\n ",c.getDifference(),c.getAccValue());
but c.getAccValue() always gives me the wrong output and I have no idea why. The formula for getDifference() is getAccValue() - principal, and that output is correct.
I used input 5000 8.25 5 quarterly
CD class:
package cd;
public class CD {
private int time; //in years, t
private double interest; //interest rate, r
private int principal; //principal, p
private String number;//number of times compounded, n
public CD(int time, double interest, int principal, String number){
this.time = time;
this.interest = interest;
this.principal = principal;
this.number = number;
}
public int getTime(){
return time;
}
public double getInterest(){
return interest;
}
public int getPrincipal(){
return principal;
}
public String getNumber(){
return number;
}
public double getAccValue(){
double A = 0;
interest = interest/100;
if( "daily".equals(number)) {
A = Math.pow(1 + interest/365, 365*time) * principal;
}
else if ("weekly".equals(number)){
A = Math.pow(1 + interest/52, 52*time) * principal;
}
else if ("monthly".equals(number)){
A = Math.pow(1 + interest/12, 12*time) * principal;
}
else if ("quarterly".equals(number)){
A = Math.pow(1 + interest/3, 3*time) * principal;
}
else if ("semiannually".equals(number)){
A = Math.pow(1 + interest/2, 2*time) * principal;
}
else if ("annually".equals(number)){
A = Math.pow(1 + interest/1, 1*time) * principal;
}
return A;
}
public double getDifference(){
return getAccValue() - principal;
}
}
CDTest class:
package cd;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class CDTest {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String input = JOptionPane.showInputDialog("Enter Principal value, "
+ "Interest rate, time (in years), " + " and number of months"
+ " compunded" + "\n(Separated by spaces)");
Scanner in = new Scanner(input);
int principal = in.nextInt();
double interest = in.nextDouble();
int time = in.nextInt();
String number = in.next();
CD c = new CD(time, interest, principal, number);
System.out.println("Principal " + "Interest " + "Maturity " +
"Number Compounded " + "Amount Gained " +
"Accumulated Value " + "");
System.out.println("========= " + "======== " + "======== "
+ "================= " + "============= " +
"================= ");
System.out.printf(" $" + c.getPrincipal() + "\t ");
System.out.print(c.getInterest() + "%" + "\t ");
System.out.print(c.getTime() + "\t ");
System.out.print(c.getNumber() +" \t");
System.out.printf("$%.2f\t $%.2f\n ",c.getDifference(),c.getAccValue());
}
}
Thanks for the help in advance
Edit:
Current output is:
Principal Interest Maturity Number Compounded Amount Gained
========= ======== ======== ================= =============
$5000 8.25% 5 quarterly $2510.99
Accumulated Value
=================
$5020.66
Expected output is:
Principal Interest Maturity Number Compounded Amount Gained
========= ======== ======== ================= =============
$5000 8.25% 5 quarterly $2510.99
Accumulated Value
=================
$7510.99
else if ("quarterly".equals(number)){
A = Math.pow(1 + interest/3, 3*time) * principal;
You're multiplying by 3. But there are 4 quarters in a year. So, I would double check this formula.
Also, you have this line:
interest = interest/100;
in getAccValue. This permanently changes the interest rate. But, getAccValue is called by getDifference. So when the difference is calculated, it divides the interest rate by 100 - and then when getAccValue is called by itself, it divides the interest rate by 100 again. So now your interest rate is tiny and it's showing hardly any money made at all.

I have a multi-dimensional array of doubles (Double[][]) created in a child class and I need to print this array in parent class

All of my main methods take place in this class:
package wk2individual;
import java.util.Scanner;
public class Wk2Individual {
public static void main(String[] args) {
AnnualPayCalculator aPC = new AnnualPayCalculator();
SalesPerson sP = new SalesPerson();
//System greeting
Scanner sc = new Scanner (System.in);
System.out.println ("Welcome to the Employee Annual Pay calculator!");
//user input
System.out.println("Please enter the name of the first sales employee:");
sP.salesPerson1 = sc.next();
System.out.println ("Please enter " + sP.salesPerson1 + "'s total sales for the year:");
aPC.totalSales1 = sc.nextDouble();
//begin outputs
if (aPC.totalSales1 >= 112000 && aPC.totalSales1 < 140000) {
System.out.println(sP.salesPerson1 + " has earned $" + aPC.total1() + " in "
+ "commissions for the year! " + sP.salesPerson1 + "'s total pay for the "
+ "year will be $" + aPC.total2()); //outputs employees commission and pay if sales meet incentive
}
else if (aPC.totalSales1 >= 140000) {
System.out.println(sP.salesPerson1 + " has earned $" + aPC.total3() + " in "
+ "commissions for the year! " + sP.salesPerson1 + "'s total pay for the "
+ "year will be $" + aPC.total4()); //outputs employees commission and pay if sales exceed targetSales
}
else if (aPC.totalSales1 < 112000) {
System.out.println(sP.salesPerson1 + " will receive a total pay of $" +
aPC.fixedSalary + " for the year. " + sP.salesPerson1 + " did not meet "
+ "the sales incentive to earn commission for the year."); /*outputs employees end of year pay as fixed
salary since the sales amount is less than 80% of the sales target*/
}
//begin the inputs for the second salesperson
System.out.println("Now let's get the name of the second sales employee:");
sP.salesPerson2 = sc.next();
System.out.println("Please enter " + sP.salesPerson2 + "'s total sales for the year:");
aPC.totalSales2 = sc.nextDouble();
//begin outputs
if (aPC.totalSales2 >= 112000 && aPC.totalSales2 < 140000) {
System.out.println(sP.salesPerson2 + " has earned $" + aPC.total5() + " in "
+ "commissions for the year! " + sP.salesPerson2 + "'s total pay for the "
+ "year will be $" + aPC.total6()); //outputs employees commission and pay if sales meet incentive
}
else if (aPC.totalSales2 >= 140000) {
System.out.println(sP.salesPerson2 + " has earned $" + aPC.total7() + " in "
+ "commissions for the year! " + sP.salesPerson2 + "'s total pay for the "
+ "year will be $" + aPC.total8()); //outputs employees commission and pay if sales exceed targetSales
}
else if (aPC.totalSales2 < 112000) {
System.out.println(sP.salesPerson2 + " will receive a total pay of $" +
aPC.fixedSalary + " for the year. " + sP.salesPerson2 + " did not meet "
+ "the sales incentive to earn commission for the year."); /*outputs employees end of year pay as fixed
salary since the sales amount is less than 80% of the sales target*/
}
//This is where I am trying to print the array created in the SalesPerson class
System.out.println("");
System.out.println("Here are both employee's sales in comparison:");
System.out.println(sP.salesPerson1 + "\t" + sP.salesPerson2);
System.out.print(n);
}
}
I created the AnnualPayCalculator class to hold the totals and calculations:
package wk2individual;
public class AnnualPayCalculator
{
double totalSales1, totalSales2, employee1TotalPay, employee2TotalPay;
double fixedSalary = 75000.00;
final double commissionRate = .25;
double salesTarget = 140000;
double accelerationFactor = .3125;
double total1(){
double incentiveCommission = totalSales1 * commissionRate;
return incentiveCommission;
}
double total2(){
double employee1TotalPay = total1() + fixedSalary;
return employee1TotalPay;
}
double total3(){
double targetCommission = totalSales1 * accelerationFactor;
return targetCommission;
}
double total4(){
double employee1TotalPay = total3() + fixedSalary;
return employee1TotalPay;
}
double total5(){
double incentiveCommission = totalSales2 * commissionRate;
return incentiveCommission;
}
double total6(){
double employee2TotalPay = total5() + fixedSalary;
return employee2TotalPay;
}
double total7(){
double targetCommission = totalSales2 * accelerationFactor;
return targetCommission;
}
double total8(){
double employee2TotalPay = total7() + fixedSalary;
return employee2TotalPay;
}
}
Then I created this SalesPerson class in which holds my array:
package wk2individual;
public class SalesPerson {
String salesPerson1, salesPerson2;
public static void main(String[] args) {
AnnualPayCalculator aPC = new AnnualPayCalculator();
Double[][] sales = new Double[2][2];
sales[0][0] = aPC.totalSales1;
sales[0][1] = aPC.totalSales2;
sales[1][0] = aPC.employee1TotalPay;
sales[1][1] = aPC.employee2TotalPay;
printArray(sales);
};
private static void printArray(Double[][] numbers){
for (Double[] n : numbers){
System.out.print(n);
}
}
In the first class I am able to print the totals of the calculations defined in the AnnualPayCalculator class. How can I print the array in the first class?
You probably don't want 2 main methods. When you create an object of SalesPerson in Wk2Individual, the 2d array sales is not being declared because static methods and variables are not part of instances/objects of classes. So what you might want to do is make a non-static method in SalesPerson like this;
public class SalesPerson {
String salesPerson1, salesPerson2;
public void createSales(AnnualPayCalculator aPC) {
// you don't need to create aPC
// AnnualPayCalculator aPC = new AnnualPayCalculator();
Double[][] sales = new Double[2][2];
sales[0][0] = aPC.totalSales1;
sales[0][1] = aPC.totalSales2;
sales[1][0] = aPC.employee1TotalPay;
sales[1][1] = aPC.employee2TotalPay;
printArray(sales);
}
}
Also, you are probably trying to use the values from the aPC object in the Wk2Individual class. But you are creating a new instance of the object instead. So you should pass the old aPC object from Wk2Individual class like this:
System.out.println("");
System.out.println("Here are both employee's sales in comparison:");
System.out.println(sP.salesPerson1 + "\t" + sP.salesPerson2);
sP.createSales(aPC);
This will send the aPC object with all the calculated values to the createSales() of SalesPerson class where your 2d array will be created.
Now you need to print this. To do that create a print method in the SalesPerson class:
private void printArray(Double[][] numbers){
for (Double[] n : numbers){
System.out.print(n);
}
}
But you cannot print an array like that. So do this:
System.out.println(Arrays.toString(n));
In AnnualPayCalculator class you have several methods which use the global variables: employee1TotalPay and employee2TotalPay. For example, the method total2(). In these methods, you are creating yet another variable with the same name. In total2() you are creating employee1TotalPay which shadows the global variable employee1TotalPay. It means that if inside that method you use employee1TotalPay anywhere, it will use the local employee1TotalPay variable (the one you created inside the method). To use the global variable either remove the declaration of the local variable:
employee1TotalPay = total1() + fixedSalary;
or use the this keyword to access the global variables:
this.employee1TotalPay = total1() + fixedSalary;

I m creating a cashier class but i cannot get name and price of each item to display

I was asked to create a cashier, testcashier and get data java classes to mimic a simple cashier operation. I created all the classes and everything including making and displaying change works but the items names and prices are not being displayed, why?
public class Cashier {
private int numberOfItems;
private double totalSum;
private double amount;
private String names;
private String s, name;
private double price, tendered, change, dollars, quarters, dimes,
nickels, pennies;
NumberFormat nf = NumberFormat.getInstance();
DecimalFormat df = (DecimalFormat)nf;
public Cashier(){
this.name = "";
this.price = price;
price = 0;
this.s = "";
}
public Cashier(String name, double price, String s)
{
//this.tendered = 0;
this.name= name;
this.price = price;
//amount = tendered;
//price = 0;
//this.s = s;
}
public double average()
{
return totalSum/numberOfItems;
}
public void add(String name, double price)
{
totalSum = totalSum + price;
s = s + name + "........" + price + "\n";
numberOfItems++;
}
public void makeChange()
{
change = amount - totalSum;
change = 100 * change;
change = Math.round(change);
change = change / 100;
dollars = (int)(amount - totalSum) * 100 / 100;
pennies = (int)(change * 100) % 100;
quarters = (int)pennies / 25;
pennies = (int)pennies % 25;
dimes = (int)pennies / 10;
pennies = (int)pennies % 10;
nickels = (int)pennies / 5;
pennies = (int)pennies % 5;
pennies = (int)pennies;
}
public String getNames()
{
return name;
}
public double getPrices()
{
return price;
}
public double getTotal()
{
return totalSum;
}
public double getMoney()
{
return tendered;
}
public double getChange()
{
return tendered - totalSum ;
}
public double getQuantity()
{
return numberOfItems;
}
public double getAverage()
{
return average();
}
public double getDollars()
{
return dollars;
}
public double getQuarters()
{
return quarters;
}
public double getDimes()
{
return dimes;
}
public double getNickels()
{
return nickels;
}
public double getPennies()
{
return pennies;
}
public void tendered(double amount)
{
// double tendered;
tendered = amount;
}
}
public class TestCashier {
public static void main(String[] args) {
Cashier c = new Cashier();
String name = GetData.getWord("Enter name of item");
double price = GetData.getDouble("Enter price of item");
c.add(name, price);
name = GetData.getWord("Enter name of item");
price = GetData.getDouble("Enter price of item");
c.add(name, price);
name = GetData.getWord("Enter name of item");
price = GetData.getDouble("Enter price of item");
c.add(name, price);
// Add a two more entries of your own
// Now average the price of the items
c.average();
// Make payment
double amount = GetData.getDouble("Enter amount of money for payment");
c.tendered(amount);
//ndered(amount); // Twenty dollars were tendered
c.makeChange();
generateReceipt(c);
}
public static void generateReceipt(Cashier c)
{
String s= "ABC Groceries Shop \n";
s = s + "Welcome – thanks for stopping, \n";
DateFormat df = DateFormat.getDateInstance();
Date d = new Date();
NumberFormat f = NumberFormat.getCurrencyInstance();
s = s + "Today is " + df.format(d) + "\n";
s = s + "Item:" +(c.getNames());
//\n";
s = s + c.getNames() + "..... " + f.format(c.getPrices()) + "\n" + c.getNames() +
"..... " + f.format(c.getPrices()) + "\n" + c.getNames() + "....." +
f.format(c.getPrices()) + "\n";
s = s + "____________________" + "\n";
s = s + "Total " + f.format(c.getTotal()) + "\n\n";
s = s + "Amount tendered " + f.format(c.getMoney()) + "\n";
s = s + "The change is " + f.format(c.getChange()) + "\n";
s = s + "There were " + c.getQuantity() + " items" + "\n";
s = s + "The average price is " + f.format(c.getAverage()) + "\n\n";
s = s + "The change includes :" + "\n";
s = s + c.getDollars() + " dollars" + "\n" + c.getQuarters()+ " quarters" +
"\n" + c.getDimes()+ " dimes" + "\n" + c.getNickels()+ " nickels" +
"\n" + c.getPennies() + " cents";
JTextArea text = new JTextArea(s,15, 25);
JScrollPane pane = new JScrollPane(text);
JOptionPane.showMessageDialog(null,pane, "Your bill",
JOptionPane.INFORMATION_MESSAGE);
}
}
public class GetData {
static String str;
static double getDouble(String s)
{
str = JOptionPane.showInputDialog(s);
return Double.parseDouble(str);
}
static int getInt(String s)
{
str = JOptionPane.showInputDialog(s);
return Integer.parseInt(str);
}
static String getWord(String s)
{
//str = JOptionPane.showInputDialog(s);
return JOptionPane.showInputDialog(s);
}
}
Your public void add(String name, double price) method concatenates the names and prices to the s member of the Cashier class, but you print the output of the getNames() and getPrices() methods, which return members that remain empty.
One way to get the output you want is to call a method that returns s and print it.
You need to instantiate Cashier using the contructor
public Cashier(String name, double price, String s)
as in
Cashier c = new Cashier (name, price, "");
not
c.add (name, price);
which does not set the field's values

java print statements clashing when user enters values

Im solving a question on java and im having some problems, im a beginner so plse help , my print statements(name and department) clash with each other when taking values from the user.
public class payroll2
{
public static void main(String args[])
{
payroll2 payroll = new payroll2();
payroll.SetPayrollDetail();
payroll.SetBonus();
payroll.SetCommission();
payroll.SetNssf();
payroll.SetNetSalary();
payroll.GetPayroll();
}
Scanner myScanner=new Scanner(System.in);
int empID;
String empName;
String empDept;
String designation;
int basicSalary;
double netSal;
double bonus;
double commission;
double nssf;
public void SetPayrollDetail()
{
System.out.println("Enter ID: ");
empID = myScanner.nextInt();
System.out.println("Enter Name: ");
empName = myScanner.nextLine();
System.out.println("Enter Department (Marketing or Other): ");
empDept = myScanner.nextLine();
System.out.println("Enter Designation (Manager, Executive or Other):");
designation = myScanner.nextLine();
System.out.println("Enter Basic Salary: ");
basicSalary = myScanner.nextInt();
}
public void SetBonus()
{
if(basicSalary < 1500){
bonus = 0.0;
}
else if(basicSalary>=1500 && basicSalary<3000){
bonus = basicSalary * (12.0/100.0);
}
else if(basicSalary>=3000 && basicSalary<5000){
bonus = basicSalary * (15.0/100.0);
}
else{
bonus = basicSalary * (25.0/100.0);
}
}
public void SetCommission()
{
if( empDept.equalsIgnoreCase("other") ){
commission = 0.0;
}
else if( empDept.equalsIgnoreCase("marketing") && designation.equalsIgnoreCase("manager") ){
commission = basicSalary * (30.0/100.0);
}
else if( empDept.equalsIgnoreCase("marketing") && designation.equalsIgnoreCase("executive") ){
commission = basicSalary * (15.0/100.0);
}
else if( empDept.equalsIgnoreCase("marketing") && designation.equalsIgnoreCase("other") ){
commission = basicSalary * (10.0/100.0);
}
else{
commission = 0.0;
}
}
public void SetNssf()
{
if(basicSalary < 1500){
nssf = basicSalary * (5.0/100.0);
}
else if(basicSalary>=1500 && basicSalary<3000){
nssf = basicSalary * (8.0/100.0);
}
else if(basicSalary>=3000 && basicSalary<5000){
nssf = basicSalary * (12.0/100.0);
}
else if(basicSalary>=5000 && basicSalary<7000){
nssf = basicSalary * (15.0/100.0);
}
else if(basicSalary>=7000 && basicSalary<10000){
nssf = basicSalary * (20.0/100.0);
}
else{
nssf = basicSalary * (25.0/100.0);
}
}
public void SetNetSalary()
{
netSal=(basicSalary + commission + bonus) - nssf;
}
public void GetPayroll()
{
System.out.println("\n\n\n\t\tPayroll Details \n____________________________________________________\n");
System.out.println("Employee Id : " + empID + "\t\t Bonus : " + bonus);
System.out.println("Name : " + empName + "\t\t\t\t Commission : " + commission);
System.out.println("Department : " + empDept + "\t\t NSSF : " + nssf);
System.out.println("Designation : " + designation + "\t\t NetSalary : " + netSal);
System.out.println("Basic Salary : " + basicSalary + "\n");
}
}
Edit on:
public void SetPayrollDetail()
{
System.out.println("Enter ID: ");
empID = myScanner.nextInt();
System.out.println("Enter Name: ");
empName = myScanner.next();
System.out.println("Enter Department (Marketing or Other): ");
empDept = myScanner.next();
System.out.println("Enter Designation (Manager, Executive or Other):");
designation = myScanner.next();
System.out.println("Enter Basic Salary: ");
basicSalary = myScanner.nextInt();
}
myScanner.next();

Categories