'How to set discount for each position in order class
I have got a program where I set price and quantity for each position in Position class. In Order class I calculate products and give discount. I have calculateDiscount method where I sum discount for all products. I would like to make discount for each position but I don't know how. I ask a some suggestion.
package programming.com.pl;
public class Position {
private String name;
private double price = 0;
private int quantity = 0;
public Position(String name, double price, int quantity){
this.name = name;
this.price = price;
this.quantity = quantity;
}
public double getPrice() {
return price;
}
public int getQuantity() {
return quantity;
}
public String toString(){
String str = String.format("%4s,%4s zł,%2s szt.", name,price,quantity);
return str;
}
}
package programming.com.pl;
import java.util.ArrayList;
public class Order {
final private ArrayList<Position> positions = new ArrayList<>();
private double calculateProduct() {
double sum = 0;
for (Position position : positions) {
sum = position.getPrice();
}
return sum;
}
double sumOrder() {
double sum = 0;
for (Position x : positions) {
sum += calculateProduct();
}
return sum;
}
void addPosition(Position p) {
positions.add(p);
}
void deletePosition(int index) {
positions.remove(index);
}
double calculateDiscount() {
double salePrice = 0;
for (Position position : positions) {
if (position.getQuantity() >= 5 && position.getQuantity() <= 10) {
salePrice = calculateProduct() - (calculateProduct() * 0.05);
} else if (position.getQuantity() <= 10 && position.getQuantity() <= 20) {
salePrice = calculateProduct() - (calculateProduct() * 0.1);
} else {
salePrice = calculateProduct() - (calculateProduct() * 0.15);
}
}
return salePrice;
}
public String toString() {
StringBuilder sb = new StringBuilder("Order is: \n");
for (Position p : positions) {
sb.append(p).append("\n");
}
sb.append("Order sum is: ").append(sumOrder()).append("\n");
sb.append("Discount is: ").append(calculateDiscount());
return sb.toString();
}
}
Solution 1:[1]
Not exactly sure what you're asking here. Are you trying to update the salePrice with a discount based on quantity? If so just update it within the relevant if loop, for example if quantity between 5 and 10 applies a 5% discount then:
salePrice = (salePrice = calculateProduct() - (calculateProduct() * 0.05)) * 0.95
If the discount is to be applied elsewhere then just set a var for each quantity case:
if (position.getQuantity() >= 5 && position.getQuantity() <= 10) {
salePrice = calculateProduct() - (calculateProduct() * 0.05);
discount = 0.95
}
And apply that discount to the price by multiplying, wherever necessary.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | neversnow1 |
