Search code examples
javaswingjoptionpane

Java simple commission program, return data based on search (JOptionPane)


I'm creating a simple commission program with the data of the sales people already in the code. I just want to find a way to search for a NAME and return their name total salary. I've hit a roadblock for the past few hours trying to do this.

public class SalesPeople {

String personName;
double annualSalary;
double salesAmount;
double percentComission;

public SalesPeople(String xPersonName, double xAnnualSalary, double xSalesAmount, double xPercentComission) {
    personName = xPersonName;
    annualSalary = xAnnualSalary;
    salesAmount = xSalesAmount;
    percentComission = xPercentComission;
}

double totalSalary = annualSalary + (salesAmount * percentComission);

public String getPersonName() {
    return personName;
}
public double getAnnualSalary() {
    return annualSalary;
}
public double getSalesAmount() {
    return salesAmount;
}
public double getPercentComission() {
    return percentComission;
}
public double getTotalSalary() {
    return totalSalary;
}
}

In the last few lines of the class below are where I'm having trouble.

import java.util.ArrayList;

import javax.swing.JOptionPane;
public class CommissionCalc {
    public static void main (String [] args ) {

        ArrayList<SalesPeople> salesList = new ArrayList<SalesPeople>();


        // PersonName, AnnualSalary, SalesAmount, PercentComission

        SalesPeople salesPerson1 = new SalesPeople ("Bob", 30000, 5000, .09);
        SalesPeople salesPerson2 = new SalesPeople ("Jane", 40000, 7000, .10);

        salesList.add(salesPerson1);
        salesList.add(salesPerson2);


        String userInput;

        userInput = JOptionPane.showInputDialog("Enter the name of a sales person:");


        if((salesList.get(0).getPersonName()).equals(userInput)) {

        for (int cnt = 0; cnt < salesList.size(); cnt++)  {
            if((salesList.get(cnt).getPersonName()).equals(userInput)) {
                System.out.println(salesList.get(cnt).getPersonName() + salesList.get(cnt).getTotalSalary());
            }
        }
            }
        }


}           
}
}

The name prints, but I'm getting a return of 0.0 on total salary. I just can't get it to return the Name and TotalSalary. Any help would really be appreciated.


Solution

  • You need to use System.out.println(salesList.get(cnt).getPersonName()); instead of System.out.println(salesList.get(cnt));. For name and total salary use code like this:

    System.out.println("Person name: " + salesList.get(cnt).getPersonName() + ", Total salary: " + salesList.get(cnt).getPersonName().getTotalSalary());
    

    For total salary, replace your getTotalSalary() method with this code:

    public double getTotalSalary() {
        return getAnnualSalary() + (getSalesAmount() * getPercentComission());
    }