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
Related
I have to do this program where I have to display the calculation of the profit for each individual stock, but I also have to display the profit for the total amount of stocks. My code only has it so it displays the calculation for all of the stocks:
import java.util.Scanner;
public class KNW_MultipleStockSales
{
//This method will perform the calculations
public static double calculator(double numberShare, double purchasePrice,
double purchaseCommission, double salePrice,
double salesCommission)
{
double profit = (((numberShare * salePrice)-salesCommission) -
((numberShare * purchasePrice) + purchaseCommission));
return profit;
}
//This is where we ask the questions
public static void main(String[] args)
{
//Declare variables
Scanner scanner = new Scanner(System.in);
int stock;
double numberShare;
double purchasePrice;
double purchaseCommission;
double salePrice;
double saleCommission;
double profit;
double total = 0;
//Ask the questions
System.out.println("Enter the stocks you have: ");
stock = scanner.nextInt();
//For loop for the number stock they are in
for(int numberStocks=1; numberStocks<=stock; numberStocks++)
{
System.out.println("Enter the number of shares for stock " + numberStocks + ": ");
numberShare = scanner.nextDouble();
System.out.println("Enter the purchase price" + numberStocks + ": ");
purchasePrice = scanner.nextDouble();
System.out.println("Enter the purchase commissioned:" + numberStocks + ": ");
purchaseCommission = scanner.nextDouble();
System.out.println("Enter the sale price:" + numberStocks + ": ");
salePrice = scanner.nextDouble();
System.out.println("Enter the sales commissioned:" + numberStocks + ": ");
saleCommission = scanner.nextDouble();
profit = calculator(numberShare, purchasePrice, purchaseCommission,
salePrice, saleCommission);
total = total + profit;
}
//Return if the user made profit or loss
if(total<0)
{
System.out.printf("You made a loss of:$%.2f", total);
}
else if(total>0)
{
System.out.printf("You made a profit of:$%.2f", total);
}
else
{
System.out.println("You made no profit or loss.");
}
}
}
How can I get it so each individual stock profit gets shown, with the profit of all the stocks together?
Try maintaining a separate Map for profit/loss. You may want to accept Stock Name as an input which will help manage individual stocks effectively.
// Map of stock name and profit/loss
Map<String,Double> profitMap = new HashMap<String,Double>();
After calculating profit/loss, add entry to map
profitMap.put("stockName", profit);
total = total + profit;
At the end of your program, iterate and display profit/loss for each Stock from Map.
for (Entry<String, Integer> entry : profitMap.entrySet()) {
System.out.println("Stock Name : " + entry.getKey() + " Profit/loss" + entry.getValue());
}
I am just about finished with a basic Cash Register program. Almost everything is working except the very end of the output where I have to show the daily total sales.
Cash Register class
public class CashRegister
{
private double purchase;
private double payment;
private double totalTax;
private double taxRate;
private double tax;
private double salesTotal;
private double salesCount;
private double amount;
private double rate;
private double taxPurchase;
private double taxable;
/**
Constructs a cash register with no money in it.
*/
public CashRegister(double rate)
{
purchase = 0;
payment = 0;
taxRate = rate;
}
/**
Records the sale of an item.
#param amount the price of the item
*/
public void recordPurchase(double amount)
{
purchase = purchase + amount;
salesTotal = amount + salesTotal;
}
/**
Records the sale of a taxable item and compute the total tax.
#param amount the price of the item
*/
public void recordTaxablePurchase(double amount)
{
//taxPurchase = taxPurchase + amount;
totalTax = totalTax + amount + (amount* (taxRate / 100));
}
/**
Enters the payment received from the customer.
#param amount the amount of the payment
*/
public void enterPayment(double amount)
{
payment = amount;
}
/**
Returns the total tax due
#return the totalTax
*/
public double getTotalTax()
{
return totalTax;
}
/**
Computes the change due and resets the machine for the next customer.
#return the change due to the customer
*/
public double giveChange()
{
double change = payment - purchase - totalTax;
salesTotal += purchase;
purchase = 0;
payment = 0;
//totalTax = 0;
salesCount++;
salesTotal++;
return change;
}
public double getSalesTotal(){
return purchase + totalTax;
}
public double getSalesCount(){
return salesCount;
}
public void reset(){
amount = 0;
purchase = 0;
totalTax = 0;
salesTotal = 0;
salesCount = 0;
}
public double showPayment(){
return payment;
}
public double getTotalPurchase(){
return payment + totalTax;
}
}
The Cash Register tester class
public class CashRegisterTester{
public static void main(String [] args){
CashRegister cash1 = new CashRegister(7.5);
System.out.println("Customer 1:");
cash1.recordPurchase(20.00);
cash1.enterPayment(20.00);
System.out.println(" Change is: " + cash1.giveChange());
System.out.println(" Expected is 0.0");
System.out.println();
System.out.println("Customer 2:");
cash1.recordPurchase(30.00);
cash1.recordPurchase(10.00);
cash1.enterPayment(50.00);
System.out.println(" Change is: " + cash1.giveChange());
System.out.println(" Expected is 10.0");
//cash1.reset();
System.out.println();
System.out.println("Customer 3:");
cash1.recordTaxablePurchase(80.00);
cash1.recordPurchase(70.00);
cash1.recordTaxablePurchase(50.00);
cash1.enterPayment(220.00);
System.out.println(" Total Sales: " + cash1.getSalesTotal());
System.out.println(" Payment Given: " + cash1.showPayment());
System.out.println(" Change is: " + cash1.giveChange());
System.out.println(" Expected is: 7.0");
System.out.println();
System.out.println(" Daily Totals: ");
System.out.println(" Total Sales: " + "$ " + cash1.getSalesTotal());
System.out.println(" Number of Sales: " + cash1.getSalesCount());
}
}
The current output is :
Customer 1:
Change is: 0.0
Expected is 0.0
Customer 2:
Change is: 10.0
Expected is 10.0
Customer 3:
Total Sales: 209.75
Payment Given: 220.0
Change is: 10.25
Expected is: 7.0
Daily Totals:
Total Sales: $ 139.75
Number of Sales: 3.0
Everything is correct except for the total sales under Daily Totals, which should be 269.75. I am confused as to why this will not work. Any help would be great, thank you.
Each time you call giveChange() you're resetting your purchase amounts back to 0. Your giveSalesCount therefore is only returning the total purchases that are totalled from your taxable sales.
Either store the payment amount elsewhere when you're calculating the change or find another way to make that calculation without removing your purchases.
public class Purchase
{
int invoiceNumber = 1234;
double salePrice = 10.00;
double SalesTax;
public void setInvoiceNumber(int invoice)
{
invoiceNumber = invoice;
}
public void setSalePrice(double saleAmount)
{
salePrice = saleAmount;
SalesTax = (saleAmount * .05);//when I'm compiling it's not calculating
}
public void displaySalePrice()
{
System.out.println("Your invoice number is:" + invoiceNumber + ".");
System.out.println("Your sale amount is: " + salePrice + ".");
System.out.println("Your sales tax is: " + SalesTax + ".");
}
}
Your invoice number is:1234.
Your sale amount is: 10.0.
Your sales tax is: 0.0.-------Problem area
----jGRASP wedge2: exit code for process is 0.
----jGRASP: operation complete.
This will work...
public class Purchase
{
int invoiceNumber = 1234;
double salePrice = 10.00;
double SalesTax = 0.0; // by default this is initialized to zero.
public void setInvoiceNumber(int invoice)
{
invoiceNumber = invoice;
}
public void setSalePrice(double saleAmount)
{
salePrice = saleAmount;
SalesTax = (saleAmount * .05);//when I'm compiling it's not calculating
}
public void displaySalePrice()
{
System.out.println("Your invoice number is:" + invoiceNumber + ".");
System.out.println("Your sale amount is: " + salePrice + ".");
System.out.println("Your sales tax is: " + SalesTax + ".");
}
public static void main(String args[])
{
setSalePrice(10.0); // sets SalesTax to (100.0 * .05)
displaySalePrice();
}
}
Note that there are some stylistic issues with this class.
"SalesTax" starts with an upper case letter, which is supposed to be reserved for class (and interface) names. The correct spelling is "salesTax".
It lacks a constructor.
Example Constructor:
public Purchase(int invoiceN, double salesP, doubles salesT) {
invoiceNum = invoiceN;
salesPrice = salesP;
salesTax = salesT;
}
A purchase is a thing that doesn't change once it is made. Its data members are variable (change-able), but they should be invariable (final or constant).
final int invoiceNumber; // These are set in the Constructor.
final double salePrice; // Once they are set, they don't change.
final double salesTax;
The class has setters (which set/change the variables), but it lacks getters (which retrieve the values of the variables without changing them). In general, variables should be declared "private" and "final" whenever possible. So if I wrote this class, I would have written it like this:
Revised example:
public class Purchase
{
private final int invoiceNumber;
private final double salePrice;
private final double salesTax;
// Constructor
public Purchase(int invoiceN, double salesP) {
invoiceNum = invoiceN;
salesPrice = salesP;
salesTax = salesPrice * .05; // The Constructor can figure this out.
}
public int getInvoiceNumber()
{
return this.invoiceNumber; // "this." is optional
}
public double getSalePrice()
{
return this.salePrice();
}
public double getSalesTax()
{
return this.salesTax;
}
public void displaySalePrice()
{
System.out.println("Your invoice number is:" + getInvoiceNumber() + ".");
System.out.println("Your sale amount is: " + getSalePrice() + ".");
System.out.println("Your sales tax is: " + getSalesTax() + ".");
}
public static void main(String args[])
{
Purchase shoesPurchase = new Purchase(1234, 10.00);
shoesPurchase.displaySalePrice();
}
}
You are never using the setSalePrice method, hence your SalesTax parameter is never being initialized. You could initialize it like so: double SalesTax = salePrice * 0.05;
You are never calling setSalePrice, so the sales tax never gets set
here's one way to correct this, though really you should probably call setSalePrice before calling displaySalePrice, rather than inside of it
public void displaySalePrice()
{
setSalePrice(salePrice);
System.out.println("Your invoice number is:" + invoiceNumber + ".");
System.out.println("Your sale amount is: " + salePrice + ".");
System.out.println("Your sales tax is: " + SalesTax + ".");
}
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'm stuck. This is what I have written so far, but I don't know how to set up for a method call to prompt for the total. I need the individual totals for all items in the array to be added to get a total cost and it needs to be displayed at the end of the program. Please, any advice is helpful. I have to be to work soon and need to turn it in before I go. Thanks
MAIN FILE
package inventory2;
import java.util.Scanner;
public class RunApp
{
public static void main(String[] args)
{
Scanner input = new Scanner( System.in );
Items theItem = new Items();
int number;
String Name = "";
System.out.print("How many items are to be put into inventory count?: ");
number = input.nextInt();
input.nextLine();
Items[]inv = new Items[number];
for(int count = 0; count < inv.length; ++count)
{
System.out.print("\nWhat is item " +(count +1) + "'s name?: ");
Name = input.nextLine();
theItem.setName(Name);
System.out.print("Enter " + Name + "'s product number: ");
double pNumber = input.nextDouble();
theItem.setpNumber(pNumber);
System.out.print("How many " + Name + "s are there in inventory?: ");
double Units = input.nextDouble();
theItem.setUnits(Units);
System.out.print(Name + "'s cost: ");
double Price = input.nextDouble();
theItem.setPrice (Price);
inv[count] = new Items(Name, Price, Units, pNumber);
input.nextLine();
System.out.print("\n Product Name: " + theItem.getName());
System.out.print("\n Product Number: " + theItem.getpNumber());
System.out.print("\n Amount of Units in Stock: " + theItem.getUnits());
System.out.print("\n Price per Unit: " + theItem.getPrice() + "\n\n");
System.out.printf("\n Total cost for %s in stock: $%.2f", theItem.getName(), theItem.calculateTotalPrice());
System.out.printf("Total Cost for all items entered: $%.2f", theItem.calculateTotalPrice()); //i need to prompt for output to show total price for all items in array
}
}
}
2ND CLASS
package inventory2;
public class Items
{
private String Name;
private double pNumber, Units, Price;
public Items()
{
Name = "";
pNumber = 0.0;
Units = 0.0;
Price = 0.0;
}
//constructor
public Items(String productName, double productNumber, double unitsInStock, double unitPrice)
{
Name = productName;
pNumber = productNumber;
Units = unitsInStock;
Price = unitPrice;
}
//setter methods
public void setName(String n)
{
Name = n;
}
public void setpNumber(double no)
{
pNumber = no;
}
public void setUnits(double u)
{
Units = u;
}
public void setPrice(double p)
{
Price = p;
}
//getter methods
public String getName()
{
return Name;
}
public double getpNumber()
{
return pNumber;
}
public double getUnits()
{
return Units;
}
public double getPrice()
{
return Price;
}
public double calculateTotalPrice()
{
return (Units * Price);
}
public double calculateAllItemsTotalPrice() //i need method to calculate total cost for all items in array
{
return (TotalPrice );
}
}
In your for loop you need to multiply the units * price. That gives you the total for that particular item. Also in the for loop you should add that to a counter that keeps track of the grand total. Your code would look something like
float total;
total += theItem.getUnits() * theItem.getPrice();
total should be scoped so it's accessible from within main unless you want to pass it around between function calls. Then you can either just print out the total or create a method that prints it out for you.
The total of 7 numbers in an array can be created as:
import java.util.*;
class Sum
{
public static void main(String arg[])
{
int a[]=new int[7];
int total=0;
Scanner n=new Scanner(System.in);
System.out.println("Enter the no. for total");
for(int i=0;i<=6;i++)
{
a[i]=n.nextInt();
total=total+a[i];
}
System.out.println("The total is :"+total);
}
}