This question already has answers here:
How do I declare and initialize an array in Java?
(31 answers)
Closed 7 years ago.
Is there anyone who could guide me in the right direction on how to create an array of these employees? The array is set to a constant SIZE=10; Here is the my employee class and the driver with the array I tried. Also, I am aware that most of the output will be blank (employee name, id, etc) As I already know how to write it but so far have not. Also the "1" in class name "Employee 1" is only there because I already had another file saved under employee. Very new to java as you can most likely tell. Thank you
class Employee1{
//variables
private String name;
private double grossPay;
// This is the constructor of the class Employee
public Employee1(String EmpName)
{
name = EmpName;
}
//calculates gross pay and returns
public double weeklyPay(double hoursWorked, double hourlyRate)
{
double timeAndHalf = (hourlyRate/2.0)+hourlyRate;
double dblOvtHours;
double dblOvtPay;
double regHours;
double ovtHours;
if (hoursWorked <= 40)
{
grossPay = hoursWorked*hourlyRate;
}
else if (hoursWorked > 40 && hoursWorked <= 60)
{
ovtHours = hoursWorked-40;
regHours = 40;
grossPay = (ovtHours*timeAndHalf) + (regHours*hourlyRate);
}
else if (hoursWorked > 60)
{
ovtHours = 20;
regHours = 40;
dblOvtHours = hoursWorked - 60;
dblOvtPay = hourlyRate * 2;
grossPay = (dblOvtPay*dblOvtHours) + (timeAndHalf * ovtHours)
+(regHours * hourlyRate);
}
return grossPay;
}/////////////////////////////////////////////////
/* Print the Employee details */
public String toString()
{
return "Employee Report\n" + "Name :" + "\nID number :"
+ "\nHours Worked" + "\nHourly Rate : " +"\nGross pay: " + grossPay ;
}
}
my driver class:
import java.util.Scanner;
public class EmployeeDriver{
public static void main(String args[]){
// Invoking methods for each object created
final double hourlyRatef = 10.25;
double hoursWorkedf, wPay;
double grossPayf = 0.0;
Scanner input = new Scanner(System.in);
System.out.print("Please enter the number of hours work: ");
hoursWorkedf = input.nextDouble();
//array that does not work //
Employee1 emp = new Employee1();
emp[0] = new Employee ();
/* invoke weeklyPay() method */
grossPayf= emp.weeklyPay(hoursWorkedf,hourlyRatef);
// invoke printEmployee() method
System.out.println (emp.toString());
}
}
What you are doing is creating a single object, not an array. An array would look like this:
final int SIZE = 10;
Employee1[] emp = new Employee1[SIZE];
Then each member of the array would have to be instantiated like this:
emp[0] = new Employee1();
public static final int SIZE = 10;
public static void main(String[] args) {
Employee1[] employees = new Employee1[SIZE];
}
As per Java doc:
An array is a container object that holds a fixed number of values of a single type.
In your case you are instantiating an object (Employee1 emp) and setting it at index 0. What about other indexes? You nee to run a loop and ask user for new employee and insert it at proper index ( 0-> 1 ->2 and so on).
Also your constructor accepts name of employee which you should also provide and print it in toString method. I have made some changes and the final code looks like:
public class Employee1 {
//variables
private String name;
private double grossPay;
// This is the constructor of the class Employee
public Employee1(String EmpName)
{
name = EmpName;
}
//calculates gross pay and returns
public double weeklyPay(double hoursWorked, double hourlyRate)
{
double timeAndHalf = (hourlyRate/2.0)+hourlyRate;
double dblOvtHours;
double dblOvtPay;
double regHours;
double ovtHours;
if (hoursWorked <= 40)
{
grossPay = hoursWorked*hourlyRate;
}
else if (hoursWorked > 40 && hoursWorked <= 60)
{
ovtHours = hoursWorked-40;
regHours = 40;
grossPay = (ovtHours*timeAndHalf) + (regHours*hourlyRate);
}
else if (hoursWorked > 60)
{
ovtHours = 20;
regHours = 40;
dblOvtHours = hoursWorked - 60;
dblOvtPay = hourlyRate * 2;
grossPay = (dblOvtPay*dblOvtHours) + (timeAndHalf * ovtHours)
+(regHours * hourlyRate);
}
return grossPay;
}/////////////////////////////////////////////////
/* Print the Employee details */
public String toString()
{
return "Employee Report\n" + "Name :" + name + "\nID number :"
+ "\nHours Worked" + "\nHourly Rate : " +"\nGross pay: " + grossPay ;
}
}
And the main is:
public static void main(String[] args) {
final double hourlyRatef = 10.25;
double hoursWorkedf, wPay;
double grossPayf = 0.0;
Scanner input = new Scanner(System.in);
System.out.println("How many employees you want to enter: ");
final int empSize = input.nextInt();
Employee1[] employees = new Employee1[empSize];
for (int i = 0; i <empSize; i++) {
System.out.print("Please enter the number of hours work: ");
hoursWorkedf = input.nextDouble();
employees[0] = new Employee1("John");
grossPayf = employees[0].weeklyPay(hoursWorkedf,hourlyRatef);
System.out.println (employees[0].toString());
}
}
Note: I have done only minimum changes to make the program work. There are various other things you can improve in your code. The program runs as:
How many employees you want to enter:
2
Please enter the number of hours work: 11
Employee Report
Name :John
ID number :
Hours Worked
Hourly Rate :
Gross pay: 112.75
Please enter the number of hours work: 10
Employee Report
Name :John
ID number :
Hours Worked
Hourly Rate :
Gross pay: 102.5
new code
public static void main(String[] args) {
final int SIZE=10;
final double hourlyRatef = 10.25;
double hoursWorkedf, wPay;
double grossPayf = 0.0;
String name = "Void";
Scanner input = new Scanner(System.in);
// System.out.println("How many employees you want to enter: ");
// final int empSize = input.nextInt();
Employee1[] employees = new Employee1[SIZE];
for (int i = 0; i <SIZE; i++)
{
System.out.print("Please enter the number of hours work: ");
hoursWorkedf = input.nextDouble();
System.out.print("Please enter employee name: ");
employees[i] = new Employee1(name);
grossPayf = employees[i].weeklyPay(hoursWorkedf,hourlyRatef);
System.out.println (employees[i].toString());
Related
Im trying to insert the total_cost variable into the string in the last few lines without doing the ("its" + total_cost) method. Im trying to replicate the python {total_variable} method in java basically
import java.util.Scanner;
public class Decision2 {
public static void main(String[] arrgs) {
Scanner input = new Scanner(System.in);
int ticket = 0;
double total_cost = 0;
System.out.println("How many tickets do you want to buy?");
ticket = input.nextInt();
if (ticket >= 5) {
total_cost = total_cost + (10.95 * ticket);
} else {
total_cost = total_cost + (8.95 * ticket);
}
System.out.printf("The total cost is {total_cost}");
}
}
You can use java String Format
such as
String foo = String.format("The total cost is %.2f",total_cost);
or if printing use such as
System.out.printf("The total cost is %.2f\n",total_cost);
I wanted to write a program that records bar inventory as I'm a bartender. I can't figure out how to pass the liquorCost and liquorCount data to the GetCostTotal() method below the main() method. I'm absolutely sure it's something fairly straightforward that I'm doing incorrectly but I just can't figure it out. Any help is appreciated.
My Liquor class is separate and I can post that if necessary but I don't think it's the class that's giving me the problem, it's retrieving the data input from the array to the separate method.
package inventory;
import java.util.Scanner;
public class Inventory {
public static void main(String[] args) {
System.out.println("How many bottles are you taking inventory of?: ");
Scanner keyboard = new Scanner(System.in);
int size = keyboard.nextInt();
Liquor[] inv = new Liquor[size];
for (int i = 0; i < inv.length; i++) {
inv[i] = new Liquor();
System.out.println("Enter product name: ");
inv[i].setLiquorName(keyboard.next());
System.out.println("Enter the count for the product: ");
inv[i].setLiquorCount(keyboard.nextDouble());
System.out.println("Enter the cost for the product: ");
inv[i].setLiquorCost(keyboard.nextDouble());
}
System.out.println("The sitting inventory cost of these products is: ");
//double totalCost = 0
for (Liquor inv1 : inv) {
System.out.println(inv1.getLiquorName() + ": $" + inv1.getLiquorCost() * inv1.getLiquorCount());
}
double costTotal = GetCostTotal(Liquor[] inv, double liquorCost, double liquorCount);
System.out.println("The total cost of the inventory is: "
+ costTotal);
System.exit(0);
}
public static double GetCostTotal(Liquor[] inv, double liquorCost, double liquorCount) {
double costTotal = 0;
for ( int i = 0; i < inv.length; i++) {
costTotal += (liquorCost * liquorCount);
}
return costTotal;
}
}
try this
public static void main(String[] args) {
System.out.println("How many bottles are you taking inventory of?: ");
Scanner keyboard = new Scanner(System.in);
int size = keyboard.nextInt();
Liquor[] inv = new Liquor[size];
for (int i = 0; i < inv.length; i++) {
inv[i] = new Liquor();
System.out.println("Enter product name: ");
inv[i].setLiquorName(keyboard.next());
System.out.println("Enter the count for the product: ");
inv[i].setLiquorCount(keyboard.nextDouble());
System.out.println("Enter the cost for the product: ");
inv[i].setLiquorCost(keyboard.nextDouble());
}
System.out.println("The sitting inventory cost of these products is: ");
//double totalCost = 0
for (Liquor inv1 : inv) {
System.out.println(inv1.getLiquorName() + ": $" + inv1.getLiquorCost() * inv1.getLiquorCount());
}
double costTotal = GetCostTotal(inv);
System.out.println("The total cost of the inventory is: "
+ costTotal);
System.exit(0);
}
public static double GetCostTotal(Liquor[] inv) {
double costTotal = 0;
for ( int i = 0; i < inv.length; i++) {
costTotal += (inv[i].getLiquorCost() * inv[i].getLiquorCount());
}
return costTotal;
}
Lets understand what went wrong here.Take a look at how you are trying to call the GetCostTotal() method.
double costTotal = GetCostTotal(Liquor[] inv, double liquorCost, double liquorCount);
This is incorrect. The syntax/way you are calling the method is actually used when we what to define a method. Like you did:
public static double GetCostTotal(Liquor[] inv, double liquorCost, double liquorCount) {}
Your call should be like:
double costTotal = GetCostTotal(inv);
Here, we are passing only inv because the data for liquorCost and liquorCount is available inside "each" element of array inv.
Now you can accept this argument in GetCostTotal method. Here as you are iterating using a for loop, you can read the data you needed as inv[i].getLiquorCost() and inv[i].getLiquorCount().
I suggest you can read more on defining a method and calling a method in java.
When I run the program and and put in a couple mortgages and then end the program it prints out the entire array of objects, mortgageArray[], but for some reason it is only printing out the last mortgage you entered. Not sure why can anybody help me out? I think the problem may lie when instantiating the objects into the array.
Mortgage Class
import java.util.*;
import java.lang.Math.*;
import java.text.DecimalFormat;
public class Mortgage {
private static int loanAmount;
private static int term;
private static double interestRate;
private static String accountNum;
private static String lastName;
private static double monthlyPayment;
private static double totalPayment;
public Mortgage(int loanAmount1, int term1, double interestRate1, String accountNum1){
loanAmount = loanAmount1;
term = term1;
interestRate = interestRate1;
accountNum = accountNum1;
}
public void promotional(){
Mortgage m = new Mortgage();
m.storeLastName();
m.storeAccountNum();
lastName = getLastName();
accountNum = getAccountNum();
monthlyPayment = m.calcMonthlyPayment();
totalPayment = m.calcTotalPayment();
}
public void unique(){
Mortgage m = new Mortgage();
m.storeLastName();
m.storeAccountNum();
m.storeLoanAmount();
m.storeInterestRate();
m.storeTerm();
monthlyPayment = m.calcMonthlyPayment();
totalPayment = m.calcTotalPayment();
}
public Mortgage(){
//dummy constructor
}
public static int getLoanAmount(){
return loanAmount;
}
public void storeLoanAmount(){
Scanner s = new Scanner(System.in);
System.out.println("Enter the amount of the loan (Ex:75000): ");
int loanAmount1 = s.nextInt();
while(loanAmount1 < 75000 || loanAmount1 > 1000000){
System.out.println("\tValid Loan Amounts are $75000-$1000000");
System.out.println("\tPlease re-enter loan amount without $ or commas (Ex:75000): ");
loanAmount1 = s.nextInt();
}
loanAmount = loanAmount1;
}
public static int getTerm(){
return term;
}
public void storeTerm(){
Scanner s = new Scanner(System.in);
System.out.println("Enter number of years for the loan: ");
int term1 = s.nextInt();
while(term1 < 10 || term1 > 40){
System.out.println("\tValid Loan Terms are 10-40");
System.out.println("\tPlease re-enter valid number of years: ");
term1 = s.nextInt();
}
term = term1;
}
public static double getInterestRate(){
return interestRate;
}
public void storeInterestRate(){
Scanner s = new Scanner(System.in);
System.out.println("Enter yearly interest rate (Ex: 8.25): ");
double interestRate1 = s.nextDouble();
while(interestRate1 < 2 || interestRate1 > 7){
System.out.println("\tValid Interest Rates are 2% - 7%");
System.out.println("\tPlease re-enter valid yearly interest rate (Ex: 8.25): ");
interestRate1 = s.nextDouble();
}
interestRate = interestRate1;
}
public String getLastName(){
return lastName;
}
public void storeLastName(){
Scanner s = new Scanner(System.in);
System.out.println("Enter customer's Last Name Only: ");
String lastName1 = s.nextLine();
lastName = lastName1;
}
private double calcMonthlyPayment(){
int months = term * 12;
double monthlyInterest = (interestRate / 12 / 100);
double monthlyPay = (loanAmount * monthlyInterest) / (1 - Math.pow(1+ monthlyInterest, -1 * months));
return monthlyPay;
}
private double calcTotalPayment(){
double totalPay = calcMonthlyPayment() * term * 12;
return totalPay;
}
public String getAccountNum(){
return accountNum;
}
public void storeAccountNum(){
StringBuilder accountNum1 = new StringBuilder();
Random rand = new Random();
int accNum = rand.nextInt(9900);
accNum += 100;
accountNum1.append(lastName.substring(0,4));
accountNum1.append(accNum);
accountNum = accountNum1.toString();
}
public String toString(){
DecimalFormat df = new DecimalFormat("#,###.00");
String strMonthlyPayment = ("$" + df.format(calcMonthlyPayment()));
String strTotalPayment = ("$" + df.format(calcTotalPayment()));
return("Account Number: " + accountNum + "\nThe monthly payment is " + strMonthlyPayment + "\nThe total payment is " + strTotalPayment);
}
}
MortgageApp Class
import java.util.*;
public class MortgageApp {
public static void main(String [] args){
Scanner s = new Scanner(System.in);
Mortgage m = new Mortgage();
int size = 10;
Mortgage [] mortgageArray = new Mortgage [size];
int index = 0;
for(index = 0; index < size; index++){
int choice;
System.out.println("\nPlease choose from the following choices below:");
System.out.println("\t1) Promotional Load (preset loan amount, rate, term)");
System.out.println("\t2) Unique Loan (enter in loan values)");
System.out.println("\t3) Quit (Exit the program)");
System.out.println("\n\t Please enter your selection (1-3): ");
choice = s.nextInt();
while(choice < 1 || choice > 3){
System.out.println("\t\tInvalid Choice. Please select 1, 2, or 3: ");
choice = s.nextInt();
}
if(choice == 1){
m.promotional();
String accountNum1 = m.getAccountNum();
mortgageArray[index] = new Mortgage(250000, 20, 3.2, accountNum1);
System.out.println("PROMOTIONAL LOAN...:");
System.out.println(mortgageArray[index].toString());
}
else if(choice == 2){
m.unique();
int loanAmount = m.getLoanAmount();
int term = m.getTerm();
double interestRate = m.getInterestRate();
String accountNum1 = m.getAccountNum();
mortgageArray[index] = new Mortgage(loanAmount, term, interestRate, accountNum1);
System.out.println("UNIQUE LOAN...:");
System.out.println(mortgageArray[index].toString());
}
else if(choice == 3){
System.out.println("\nPROGRAM COMPLETE");
System.out.println("Contents of Array...");
for(int j = 0; j < 10; j++){
if(mortgageArray[j] != null){
System.out.println(mortgageArray[j].toString() + "\n");
}
}
index = 10;
}
}
}
}
The problem is with your loop at the end
for(int j = 0; j < 10; j++){
if(mortgageArray[j] != null){
System.out.println(mortgageArray[1].toString() + "\n");
}
}
It always prints the element at index 1.
Should be
System.out.println(mortgageArray[j].toString() + "\n");
All your fields in the class Mortgage are static.
To fix this, simply remove the static keyword:
private int loanAmount;
private int term;
private double interestRate;
private String accountNum;
private String lastName;
private double monthlyPayment;
private double totalPayment;
Static fields don't belong to an instance, but to the class that gets instantiated. So everytime you call one of your getter-methods, the previous value (of all your instances) will be overriden.
If you are not familiar with classes and objects in Java, this tutorial might be helpfull for you: Understanding Class Members
I'm writing one of my first java codes and I can't get it to run. When I run the code it tells me there are errors but in the console at the bottom nothing appears for me to see what the error might be. Please help?
package operators;
import java.util.Scanner;
public class assignment2ifelse {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int quantity;
int packages = 99;
quantity = input.nextInt();
double dis1 = .2; // dis2 = .33, dis3 = .42, dis4 = .29;
double price = packages * quantity;
double discount = 0;
double finalprice = price * discount;
if (quantity < 20 && quantity > 9) {
System.out.println(price);
discount = price * dis1;
System.out.println(discount);
System.out.println(finalprice);
}
}
}
Try this code :
package operators;
import java.util.Scanner;
public class assignment2ifelse {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int quantity;
int packages = 99;
System.out.println("Enter a quantity : ");
quantity = input.nextInt();
double dis1 = .2; // dis2 = .33, dis3 = .42, dis4 = .29;
double price = packages * quantity;
double discount = 0;
double finalprice = price * discount;
if (quantity < 20 && quantity > 9) {
System.out.println(price);
discount = price * dis1;
System.out.println(discount);
System.out.println(finalprice);
} else {
System.out.println("Quantity doesn't match expectations.");
}
}
}
Actually, the program runs but it doesn't show you anything because it begins immediately by waiting for an input from the user:
quantity = input.nextInt();
Then, it shows you something only if your entry matches the condition of your if test.
Next time, try to create an interaction with the user by prompting them with messages using System.out.print().
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.