Need to pull commission rate from one array into the output - java

I'm in a beginners Java class and am having trouble with getting this to work. I need to get my program to pull the commission rate from one array into the output. Everything else seems to be working but it won't calculate the commission and I'm not sure what I am missing. Any help would be wonderful!
public class Annualwages extends salesperson
{
/** #param args the command line arguments */
public static void main(String[] args)
{ //begins the main method
salesperson sp = new salesperson();
sp.saleInformation();
System.out.println("You entered the following:");
System.out.println();
for (int index = 0; index < sp.salesP.length; index++)
{
System.out.println("Sales Person " + (index + 1));
System.out.println(" Name: "
+ sp.salesP[index]);
System.out.println(" Total Annual Sales: "
+ sp.sales[index]);
System.out.println(" Base Salary is: " + sp.SALARY);
System.out.println(" Annual Commission is: "
+ sp.comm[index]);
System.out.println(" Total Annual Compensation is: "
+ sp.totalWages );
System.out.println();
}
} // ends main method
} //ends annual wages class
package annualwages;
import java.util.Scanner;
class salesperson { //begins salesperson class
protected String name;
protected String[] salesP; // To reference an array of sales people
protected double[] sales; // references an array for sales achieved
protected double[] comm; // references an array for commission rate
protected int numSales; // Number of sales people & sales achieved
protected final double COMMISSION=0.15; //Sets a fixed variable for commission earned
protected final double SALARY=50000; //Sets a fixed variable for Salary earned
protected final double SALESTARGET=120000; //Sets a fixed variable for the sales target
protected double totalSales, totalWages, actualCommission, accelFactor=1.25;
public void saleInformation()
{ //begins saleInformation method
// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);
//Get number of sales people
System.out.print("How many sales people do you want to compare? ");
numSales = keyboard.nextInt();
// Creates an array to hold number of sales people.
salesP = new String [numSales];
//Gets the names of the sales people.
for (int index = 0; index < salesP.length; index++)
{
System.out.print("Enter name of sales person "
+ (index + 1) + ": ");
salesP[index] = keyboard.next();
}
//creates an array to hold amoount in sales achieved
sales = new double[numSales];
// gets the amount in sales that each sales person has achieved annually
for (int index = 0; index < sales.length; index++)
{
System.out.print("Enter amount in sales achieved per person annually "
+ (index + 1) + ": ");
sales[index] = keyboard.nextDouble();
}
// creates an array to hold the commission rate
comm = new double [numSales];
//Sales incentive begins at a minimum at $96,000 in sales.
//if less than, then no commission is earned
for (int index = 0; index < comm.length; index ++)
{
if (sales.length <= 96000)
{
actualCommission=0;
}
// Sales incentive with $96,000 or more earns 15% commission
else if ((sales.length > 96000) && (sales.length < SALESTARGET ))
{
actualCommission=COMMISSION;
}
//Sales incentive increases if the sales person earns more than $120,000
//in sales with the acceleration factor of 1.25
else
{
actualCommission=COMMISSION*accelFactor;
}
}
//Calculates total sales by multiplying sales and commission
totalSales = sales.length* comm.length;
//Calculates total wages by adding salary to total sales
totalWages = SALARY + totalSales;
} //ends saleInformation method
} //ends salesperson class

You have a few errors.
You're not assigning any value to comm[index] when you calculate the commission. Instead of using the actualCommission variable (which you never actually display), just assign directly to comm[index].
The variable sales.length is unlikely ever to be 96000 or more, since it's the number of sales you're putting in. So the first if condition is going to return true every time, and you'll end up setting the commission to zero. Perhaps you meant to write if (sales[index] <= 96000) instead. Similarly for the other comparisons involving sales.length.

Related

Payroll Array Java Calculation

Hello guys, this is my first time i post something in here and i just started learning java. This is my assignment and i need to write a payroll code with array. However, i dont understand why i cant get it to work. Somehow, it only calculate the last employee, the first and second are not included. If you guys can help i'd appreciate it. Thank you!
public class ArrayIG
{
public static void main(String[] args)
{
final int NUM_EMPLOYEES = 3;
//creating array
int[]hours = new int[NUM_EMPLOYEES];
int[] employeeID = {5678459, 4520125, 7895122};
double payRate;
double wages = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your " + NUM_EMPLOYEES + " employees work hours and pay rate:");
//get the hours
for (int i = 0; i < NUM_EMPLOYEES; i++)
{
System.out.print("Employee #" + employeeID[i] + ": ");
hours[i] = keyboard.nextInt();
//get the hourly pay rate
System.out.print("Enter the pay rate: ");
payRate = keyboard.nextDouble();
wages = hours[i] * payRate;
}
//display wages
System.out.println("The hours and pay rates you entered are:");
for(int i = 0; i < NUM_EMPLOYEES; i++)
{
System.out.printf("The total wages for Employee #%d is $%.2f\n", employeeID[i], wages);
}
}
}
MY OUTPUT:
Enter your 3 employees work hours and pay rate:
Employee #5678459: 35
Enter the pay rate: 21
Employee #4520125: 37
Enter the pay rate: 18.5
Employee #7895122: 39
Enter the pay rate: 37.25
The hours and pay rates you entered are:
The total wages for Employee #5678459 is $1452.75
The total wages for Employee #4520125 is $1452.75
The total wages for Employee #7895122 is $1452.75
Either create an array of wages or calculate wages in loop where wages are being print. And you should do assignments on your own 😀
You're collecting 3 different hours but only storing them in one value. The same for the wages. What happens when you store them as an array?
import java.util.Scanner;
public class ArrayIG
{
public static void main(String[] args)
{
final int NUM_EMPLOYEES = 3;
//creating array
int[] hours = new int[NUM_EMPLOYEES];
int[] employeeID = {5678459, 4520125, 7895122};
double[] payRate = new double[NUM_EMPLOYEES];
double[] wages = new double[NUM_EMPLOYEES];
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your " + NUM_EMPLOYEES + " employees work hours and pay rate:");
//get the hours
for (int i = 0; i < NUM_EMPLOYEES; i++)
{
System.out.print("Employee #" + employeeID[i] + ": ");
hours[i] = keyboard.nextInt();
//get the hourly pay rate
System.out.print("Enter the pay rate: ");
payRate[i] = keyboard.nextDouble();
wages[i] = hours[i] * payRate[i];
}
//display wages
System.out.println("The hours and pay rates you entered are:");
for(int i = 0; i < NUM_EMPLOYEES; i++)
{
System.out.printf("The total wages for Employee #%d is $%.2f\n", employeeID[i], wages[i]);
}
}
}
You have 3 employees -> 3 wages.
But currently you're using only one variable to hold the wage: double wages = 0;
Hence its value is replaced for every loop.
You should create an array of length 3 to store the wages:
and in your loop, replace
wages = hours[i] * payRate;
With
wages[i] = hours[i] * payRate;
And print:
System.out.printf("The total wages for Employee #%d is $%.2f\n", employeeID[i], wages[i]);
You are setting the wage rate at each iteration. I.e. you are only ever recording a single state of wages. Then you are iterating and displaying that one wages variable, which will always be the last calculation.
Store each "wages" value in an array like you have done with hours and you should resolve your issue.

Need assistance with having executable code

I haven't been able to make this code executable for class and can't find the reason why there are no errors prompting however when i execute i get this:
Exception in thread "main" java.lang.UnsupportedOperationException: Not
supported yet.
at set.fixedSalary(set.java:14)
at Main.main(Main.java:23)
C:\Users\the_h\AppData\Local\NetBeans\Cache\8.2\executor-
snippets\run.xml:53: Java returned: 1
I honestly have no idea how to fix this problem any help is appreciated I have the source code below.
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
private double fixedSalary;
private double commission;
private double salesTarget;
private double Acc_Rate;
private ArrayList<Double> annualSales;
private ArrayList name;
public static void main(String[] args){
// salesperson will earn a fixed salary of $32,600
set.fixedSalary(32600);
// The current sales target for every salesperson is $120,000.00
set.SalesTarget(120000.00);
//The acceleration factor is 2.1
set.Acc_Rate(2.1);
}
public ArrayList<Double> getAnnualSales(){
return annualSales;
}
public Main() {
this.name = new ArrayList();
this.annualSales = new ArrayList<>();
}
private float calculateCommission(double personSale) {
throw new UnsupportedOperationException("Not supported yet."); //To
change body of generated methods, choose Tools | Templates.
}
function read user input
class readData{
public void readData(){
// Creates a scanner object for sales entry.
Scanner input = new Scanner(System.in);
// prompts user for name of sales person
System.out.println("Please enter First Sales Person name: ");
name = addinput.nextLine();
// prompts user for name of sales person
System.out.println("Please enter 2nd Sales Person name: ");
name = addinput.nextLine();
//Prompts user for sales
System.out.println("Please enter annual sales First Person: ");
annualSales = addinput.nextDouble();
//Prompts user for sales
System.out.println("Please enter annual sales Second Person: ");
annualSales = addinput.nextDouble();
}
}
class calculateCommission {
double commission = 0.00;
double Acc_Rate;
calculateCommission() {
}
public double calculateCommission(double annualSales, double fixedSalary,
double salesTarget) {
this.Acc_Rate = 0.045 * annualSales;
double earnings = fixedSalary;
// The current commission is 4.5 of total sales
if(annualSales < 0.8 * salesTarget) {
earnings = fixedSalary + commission;
} else if (annualSales <= salesTarget){
//The current acc rate is 2.1 of total sales
commission = 0.045 * annualSales;
earnings = fixedSalary + commission;
} else if (annualSales > salesTarget){
earnings = fixedSalary + Acc_Rate;
}
return earnings;
}
} // function get commision
public double getCommission() {
return commission;
}
// function get total annual compensation
public double getTotalCommissionCalc(){
return fixedSalary + getCommission();
}
// funtion set value for fixedSalary
public void setfixedSalary(double fixedSalary){
this.fixedSalary = fixedSalary;
}
// funtion set value for salesTarget
public void setSalesTarget(double salesTarget){
this.salesTarget = salesTarget;
}
// funtion set value for incentive rate
public void setAcc_Rate(double Acc_Rate) {
this.Acc_Rate = Acc_Rate;
}
// Display a table of potential total annual compensation
public void displayResult(){
double annualSalesCalc;
double personSale;
for (int i = 0; i < name.size(); i++){
String personName = (String) name.get(i);
personSale = annualSales.get(i);
System.out.println("Total Compensation of Sales Person " +
personName + " is " + Math.round(calculateCommission(personSale)));
//Print column names
System.out.print("SalePerson\tTotal Sales\tTotal Compensation");
annualSalesCalc = personSale * 1.50;
while(personSale <= annualSalesCalc){
calculateCommission(personSale);
System.out.println((personName) + "\t\t" +
Math.round((personSale)) + "\t\t" +
Math.round(calculateCommission(personSale)));
personSale = personSale + 5000;
}
System.out.println(); // print blank line
}
if (annualSales.get(0) > annualSales.get(1)) {
System.out.println("Salesperson " + name.get(1)
+ "'s additional amount of sales that he must "
+ "achieve to match or exceed the higher of the salesperson
"
+ Math.round(annualSales.get(0)) + " is");
System.out.print("$" + Math.round((annualSales.get(0) -
annualSales.get(1))));
} else if(annualSales.get(1) > annualSales.get(0)){
System.out.println("Salesperson " + name.get(0)
+ "'s additional amount of sales that he must "
+ "achieve to match or exceed the higher of the salesperson
"
+ Math.round(annualSales.get(1)) + " is");
System.out.print("$" + Math.round((annualSales.get(1) -
annualSales.get(0))));
} else{
System.out.print("Both have same compensation");
}
}
}
It might be because your set.fixedSalary needs to be an integer because you dont set it as a double. you set it to 36000 when it needs to be 36000.0

How would i program this correctly?

what the program wants me to code:
Code an executable program that will produce
an invoice for a customer ordering a number
of products at a store. A sample run of the
program is shown to the right.
Your program
must ask for the number of products (up to a
maximum of 12 products may be ordered) and
then successively ask for the product name and
its cost. The invoice produced includes:
ï‚· the title of the store (as shown),
ï‚· product names and their cost,
ï‚· calculated cost of all products,
ï‚· calculated 5% sales tax,
ï‚· overall total cost
ï‚· a thank you.
The products and their cost must be kept in
parallel arrays. Two methods must be coded.
One method will display the title. The second
method will accept the calculated cost of all
products and return the calculated sales tax.
The method that computes the sales tax must
use a named constant for the 5% tax rate.
picture of example run of what it should look like: http://imgur.com/F3XDjau
Currently my program is this so far, but im not sure if it is correct or if i need to make the variables into an array.
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
int product;
String products;
double cost;
System.out.println("How many products? ");
product=input.nextInt();
for(int i = 0; i < product; i++){
System.out.println("Product Name: ");
products=input.next();
System.out.println("Cost: ");
cost=input.nextDouble();
}
}
}
this is how you can fill your array:
double[] costArray = new double[product];
for(int i = 0; i < product; i++){
costArray[i] = input.nextDouble();
}
You need to use an array for variables products and cost like this:
static final float TAXES = 0.05f;
public static void main(String[] args) {
double sum = 0.0;
double tax;
Scanner input = new Scanner(System.in);
int product;
String products[];
double cost[];
System.out.println("How many products? ");
product = input.nextInt();
products = new String[product];
cost = new double[product];
for (int i = 0; i < product; i++) {
System.out.println("Product Name: ");
products[i] = input.next();
System.out.println("Cost: ");
cost[i] = Double.parseDouble(input.next().trim().replace(',', '.'));
}
indentedText();
for (int i = 0; i < product; i++) {
System.out.printf(products[i] + '\t' + "%.2f %n", cost[i]);
sum = sum + cost[i];
}
tax = calculateTaxes(sum);
System.out.printf("Sub total:" + '\t' + "%.2f %n", sum);
System.out.printf("Sales tax:" + '\t' + "%.2f %n", tax);
System.out.printf("Total to be paid:" + '\t' + "%.2f %n %n", (sum + tax));
System.out.print('\t' + "Thank you!");
}
private static void indentedText() {
System.out.print('\t' + "The Company Store" + '\n' + '\n');
}
private static double calculateTaxes(double sum) {
return sum * TAXES;
}

Problems with adding to an ArrayList and then removing the elements

I'm sorry if this has been asked before somewhere, but I really haven't seen anything that helps with the exact question that I have. This is for school work, but I've beat myself up for 2 days over trying to figure out what I'm doing wrong, so if someone can help I would more than appreciate it.
I have a program that is basically supposed to enter the name of two sales people, show a table of their potential earnings, and finally compare the differences in their sales. I'm doing this in NetBeans IDE, and I've got all sorts of things in here trying to figure it out.
Everything works fine until I try to pull anything out of my ArrayLists. I was thinking it should be possible to store something in there, then pull it back out to do the math I need to do but I must be doing something wrong. Here's the specific Class code I'm having problems with:
class EarningDifference {
SalesPerson persons = new SalesPerson(); //Access to SalesPerson class
AnnualSales aSaleC = new AnnualSales(); //Access to AnnualSales class
ArrayList<SalesPerson> list = new ArrayList<>(); //Access to SalesPerson ArrayList
ArrayList<AnnualSales> aSales = new ArrayList<>(); //Access to AnnualSales ArrayList
AnnualSales person1EarningStr; //Person one earnings from AnnualSales ArrayList
AnnualSales person2EarningStr; //Person two earnings from AnnualSales ArrayList
Double person1Earning; //Person one earnings as double
Double person2Earning; //Person two earnings as double
String person1; //String for person one full name
String person2; //String for person two full name
Double difference; //Variable to store the difference between Person1 and Person2 sales
double totalSales; //variable for Total sales
public void people() {
person1 = list.get(0).getFirstName() + " " + list.get(0).getLastName();
person2 = list.get(1).getFirstName() + " " + list.get(1).getLastName();
System.out.println("Comparing " + person1 + " with " + person2 + ".");
}
void settotalSales(Double totalSales) {
this.totalSales = totalSales;
AnnualSales person1EarningStr = aSales.get(0);
AnnualSales person2EarningStr = aSales.get(1);
double person1Earning = person1EarningStr.doubleValue();
double person2Earning = person2EarningStr.doubleValue();
if (aSales.size() < 2) {
System.out.println("Need another person to compare");
} else if (person1Earning > person2Earning) {
difference = person1Earning - person2Earning;
System.out.println(person1 + " has earned " + difference + " more in sales than " + person2 + ".");
} else {
difference = person2Earning - person1Earning;
System.out.println(person2 + " has earned " + difference + " more in sales than " + person1 + ".");
}
}
}
Here is the class where items are added to the AnnualSales ArrayList:
public class SalaryTotal {
double fixedSalary; //Variable for the fixed salary amount
double commission; //Variable for the comission
double minimumSales; //Variable to define the minimum amount of annual sales sales persn must make to receive compensation
double maximumSales; //Variable to define the number after which commission increases
double advanceRate; //Variable used to define the rate at which compensation increases after minimum sales are met
double compensation; //Variable for the amount of compensation based on sales
double totalSalary; //Variable for the total salary
double totalSales;
Double compensationD;
SalesPerson persons = new SalesPerson();
ArrayList<SalesPerson> list = new ArrayList<>();
ArrayList<Double> aSales = new ArrayList<>();
public void getCompensation(double totalSales) {
commission = .21; //The constant commission rate
minimumSales = 120000; //The constant minimum sales needed to receive compensation
maximumSales = 150000; //The constant maximum amount above which commission increases by the advanceRate
advanceRate = 1.67; //The constant at which compensation increasea after minimum sales
this.totalSales = totalSales;
if (totalSales < minimumSales) {
compensation = 0; //sets compensation to 0 if minimum sales are not met
} else if (totalSales <= 150000){
compensation = totalSales * commission + fixedSalary; //calculates total of compensation if total sales meet minimum sales
} else if (totalSales > maximumSales) {
compensation = totalSales * commission * advanceRate + fixedSalary; //calculates total compensation if total sales exceed maximum sales
}
Double compensationD = new Double(compensation);
aSales.add(compensationD);
System.out.println("Current total compensation:" + compensation);
for (int i = 0; i < aSales.size(); i++) {
System.out.println(aSales.get(i));
System.out.println("Show " + persons.makePerson1() + ".");
}
}
}
}
I'm sure this is a complete mess of bad coding, but any help would be appreciated, just ignore the random bits of odd coding I put in to try to narrow down what my issue is. Thank you so much.
The rest of the program look like this, I've also removed the bits that were just in for problem testing from previous portions
Main:
import java.util.Scanner; //Needed for scanner input
import java.text.DecimalFormat; //Needed for correct output of decimals
import java.util.ArrayList;
public class AnnualCompensation {
private static String Y;
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("$###,###.00"); //This will correctly format the money amounts
Double totalSales;
int startY;
ArrayList<SalesPerson> list = new ArrayList<>();
ArrayList<AnnualSales> aSales = new ArrayList<AnnualSales>();
Scanner start = new Scanner(System.in); //Creates scanner input
System.out.println("Are you ready to compare sales? Press 1 if yes, 2 if no."); //Prints out entry command
startY = start.nextInt();
switch (startY){
case 1:
InputClass inputs = new InputClass();
inputs.getInputs();
break;
case 2:
System.out.println("Thank you anyway!");
System.exit(0);
break;
default:
System.out.println("You have selected neither Y or N, please try again.");
System.exit(0);
}
SalaryTotal calculator = new SalaryTotal(); //Calls class SalaryTotal
PossibleCompensation table = new PossibleCompensation(); //Calls class PossibleCompensation
}
}
Possible Compensation:
public class PossibleCompensation {
SalesPerson persons = new SalesPerson();
ArrayList<SalesPerson> list = new ArrayList<>();
ArrayList<AnnualSales> aSales = new ArrayList<AnnualSales>();
DecimalFormat df = new DecimalFormat("$###,###.00"); //This will correctly format the money amounts
double commission; //Variable for the comission
double minimumSales; //Variable to define the minimum amount of annual sales sales persn must make to receive compensation
double maximumSales; //Variable to define the number after which commission increases
double advanceRate; //Variable used to define the rate at which compensation increases after minimum sales are met
double compensation; //Variable for the amount of compensation based on sales
double totalSales; //Variable for sales person annual sale
public void settotalSales(double totalSales) {
for (int i = 0; i < list.size(); i++)
this.totalSales = totalSales; //Sets the input from AnnualCompensation to totalSales in this class
commission = .21; //The constant commission rate
minimumSales = 120000; //The constant minimum sales needed to receive compensation
maximumSales = 150000; //The constant maximum amount above which commission increases by the advanceRate
advanceRate = 1.67; //The constant at which compensation increasea after minimum sales
String heading1 = "Total Sales"; //variable to print a header for the table
String heading2 = "Total Compensation"; //variable to print a header for the table
System.out.print("\nBelow is a table based on possible commissions if sales increase:\n"); //Prints instructions
System.out.printf("\n%20s %20s", heading1, heading2); //prints header and formats spacing
for (double i=totalSales; i <= (totalSales * 1.5); i+= 5000) { //FOR loop for calculating and constructing table
if (i < minimumSales) {
compensation = 0; //sets compensation to 0 if minimum sales are not met
} else if (i <= 150000){
compensation = i * commission; //calculates total of compensation if total sales meet minimum sales
} else if (i > maximumSales) {
compensation = i * commission * advanceRate; //calculates total compensation if total sales exceed maximum sales
}
System.out.printf("\n%20s %15s", df.format(i), df.format(compensation) + "\n"); //Prints out the table
}
}
}
class SalesPerson {
String firstName;
String lastName;
String totalSalesStr;
ArrayList<SalesPerson> list = new List<>();
SalesPerson class:
public SalesPerson() {
this.firstName = firstName;
this.lastName = lastName;
this.totalSalesStr = totalSalesStr;
}
SalesPerson(String firstName, String lastName, String totalSalesStr) {
this.firstName = firstName;
this.lastName = lastName;
this.totalSalesStr = totalSalesStr;
}
public String getFirstName() {
return this.firstName;
}
public String getLastName() {
return this.lastName;
}
public String getTotalSalesStr() {
return this.totalSalesStr;
}
public Double getTotalSales() {
Double totalSales = Double.parseDouble(totalSalesStr);
return totalSales;
}
public String makePerson1() {
String person1 = list.get(0).getFirstName() + " " + list.get(0).getLastName();
return person1;
}
public String makePerson2() {
String person2 = list.get(1).getFirstName() + " " + list.get(1).getLastName();
return person2;
}
#Override
public String toString() {
return ("Sales person " + this.getFirstName() + " " + this.getLastName() + " has annual sales of " + this.getTotalSalesStr() + ".");
}
}
class AnnualSales {
Double compensationD;
AnnualSales person1EarningStr;
AnnualSales person2EarningStr;
ArrayList<AnnualSales> aSales = new ArrayList<AnnualSales>();
public AnnualSales() {
this.compensationD = compensationD;
}
public AnnualSales(Double compensationD) {
this.compensationD = compensationD;
}
public Double getCompensationD() {
return this.compensationD;
}
public AnnualSales getperson1EarningStr() {
person1EarningStr = aSales.get(0);
return person1EarningStr;
}
public AnnualSales getperson2EarningStr() {
person2EarningStr = aSales.get(1);
return person2EarningStr;
}
#Override
public String toString() {
return ("please show us" + compensationD);
}
}
Input class:
class InputClass {
String firstName;
String lastName;
Double totalSales;
String totalSalesStr;
CopyOnWriteArrayList<SalesPerson> list = new CopyOnWriteArrayList<>();
public void getInputs() {
for(double i=0; i < 2; i++){
Scanner persFN = new Scanner(System.in); //Creates scanner input
System.out.println("Enter sales person's first name:"); //Prints out entry command
String firstName = persFN.next();
Scanner persLN = new Scanner(System.in); //Creates scanner input
System.out.println("Enter sales person's last name:"); //Prints out entry command
String lastName = persLN.next();
Scanner input = new Scanner(System.in); //Creates scanner input
System.out.println("Enter Total Sales:"); //Prints out entry command
totalSales = input.nextDouble();
String totalSalesStr = totalSales.toString();
list.add(new SalesPerson(firstName, lastName, totalSalesStr));
SalaryTotal calculator = new SalaryTotal(); //Calls class SalaryTotal
calculator.getCompensation(totalSales);
PossibleCompensation table = new PossibleCompensation(); //Calls class PossibleCompensation
table.settotalSales(totalSales);
EarningDifference earning = new EarningDifference();
earning.settotalSales(totalSales);
}
}
}
I think that should be everything related!
Make sure you have override equals() method in your Classes. As a good practice always make sure you have override both equals() and hashCode().
Why?
From Java doc.
Removes the first occurrence of the specified element from this list,
if it is present. If the list does not contain the element, it is
unchanged. More formally, removes the element with the lowest index i
such that (o==null ? get(i)==null : o.equals(get(i))) (if such an
element exists). Returns true if this list contained the specified
element (or equivalently, if this list changed as a result of the
call).
If your ArrayList element not a String(more generally if it is not a inbuilt Java class), You need to override equals() method.

I am stuck on homework assignment Commission Calculation

I need to compare the total annual sales of at least three people. I need my app to calculate the additional amount that each must achieve to match or exceed the highest earner. I figured out most of it and know how to do it if there were only two people in the scenario, but getting third into the equation is throwing me for a loop! Any help is appreciated and thanks in advance! Here's what I have so far, but obviously at the end where the calculations are not going to be right.
package Commission3;
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
// Create a new object AnnualCompensation
Commission3 salesPerson[] = new Commission3[2];
// creat two object
salesPerson[0] = new Commission3();
salesPerson[1] = new Commission3();
salesPerson[2] = new Commission3();
//new scanner input
Scanner keyboard = new Scanner(System.in);
//get salesperson1 name
System.out.println("What is your first salesperson's name?");
salesPerson[0].name = keyboard.nextLine();
//get salesperson1 sales total
System.out.println("Enter annual sales of first salesperson: ");
double val = keyboard.nextDouble();
salesPerson[0].setAnnualSales(val);
//get salesperson2 name
System.out.println("What is your second salesperson's name?");
salesPerson[1].name = keyboard.next();
//get salesperson2 sales total
System.out.println("Enter annual sales of second salesperson: ");
val = keyboard.nextDouble();
salesPerson[1].setAnnualSales(val);
//get salesperson3 name
System.out.println("What is your third salesperson's name?");
salesPerson[2].name = keyboard.next();
//get salesperson3 sales total
System.out.println("Enter annual sales of third salesperson: ");
val = keyboard.nextDouble();
salesPerson[2].setAnnualSales(val);
double total1, total2, total3;
total1 = salesPerson[0].getTotalSales();
System.out.println("Total sales of " + salesPerson[0].name +" is: $" + total1);
total2 = salesPerson[1].getTotalSales();
System.out.println("Total sales of " + salesPerson[1].name +" is: $" + total2);
total3 = salesPerson[2].getTotalSales();
System.out.println("Total sales of " + salesPerson[2].name +" is: $" + total3);
if (total1 > total2) {
System.out.print("Salesperson " + salesPerson[2].name + "'s additional amount
of sales that he must " + " achieve to match or exceed the higher of the
salesperson " + salesPerson[0].name);
System.out.println(" $" + (total1 - total2));
} else if (total2 > total1) {
System.out.print("Salesperson " + salesPerson[0].name + "'s additional amount
of sales that he must " + " achieve to match or exceed the higher of the
salesperson " + salesPerson[1].name);
System.out.println(" $" + (total2 - total1));
} else {
System.out.println("Both have same compensation $" + total1);
}
}
}
When you take the input from the user, keep track of the highest sales thus far, and the name of the salesperson with the most sales.
Then, instead of checking total1 and total2, you can loop through all three, and compare them to the max. If the current total is less than the max, then calculate the difference. Otherwise, the current total is equal to the max, and you don't need to do the calculation.
I'll leave the actual code for you to figure out.

Categories