I need to implement an operation in my java program.
So I have the item, the price of it is 6,00€, but if the user get three of these items I can get a discount of 3,00€. So
int quantity = 3;
double discount = 3.0;
int quantityItem = 3;
double priceItem = 6.0;
double totalPrice = priceItem * quantityItem;
if(quantityItem == quantity){
totalePrice = totalePrice - discount;
}
The previous code is ok. But if I get 5 items the correct totalePrice should be:
priceItem (6€) * quantity (5) = 30€ – 3.0€ (discount) = 27€.
If I get 6 items the correct totalPrice should be:
priceItem (6€) * quantity (6) = 36€ – 6.0€ (discount) = 30€.
How can I write the code to make this dynamically ?
>Solution :
To identify the number of "groups of 3" of something bought, you need to divide the number bought by 3. Specifically, you want to use integer division, which basically means "divide by 3, then ignore the decimal part". So
1 / 3 = 0
2 / 3 = 0
3 / 3 = 1
4 / 3 = 1
5 / 3 = 1
6 / 3 = 2
...
In Java, division between two integers performs integer division by default, so you can calculate the number of "groups of 3" like so.
int discountQuantity = quantity / quantityItem;
Then you apply the discount that many times.
double totalPrice = priceItem * quantityItem - discountQuantity * discount;