I'm trying to create code that takes the number of items that a customer has bought, then print out how much will be discounted.
1-3 items purchased will get no discount
4-6 items purchased will get 5% discount
7-10 items purchased will get 10% discount
11 or more items purchased will get a 15% discount
Any help will be appreciated, thank you. Here is the code that i created.
package discount;
import java.util.Scanner;
public class Discount {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Input the number of items: ");
int quantity = input.nextInt();
int[] discount = {0, 5, 10, 15};
if (quantity >= 1 && quantity < 4) {
System.out.print("no discount");
} else if (quantity >= 4 && quantity < 7) {
System.out.print(discount[1] "% discount");
} else if (quantity >= 7 && quantity < 11) {
System.out.print(discount[2] "% discount");
} else if (quantity >= 11) {
System.out.print(discount[3] "% discount");
}
}
}
CodePudding user response:
I suggest you to apply decomposition by extracting the code that is responsible for calculating discounts and printing messages into separate methods. It will make your code cleaner even without switch expressions.
1. Calculate discount:
public static int getDiscount(int items) {
return switch(items) {
case 0, 1, 2, 3 -> 0;
case 4, 5, 6 -> 5;
case 7, 8, 9, 10 -> 10;
default -> 15;
};
}
2. Print the message:
public static void printMessage(int discount) {
switch(discount) {
case 0 -> System.out.print("no discount");
default -> System.out.println(discount "% discount");
}
}
3. main:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Input the number of items: ");
printMessage(getDiscount(input.nextInt()));
}
- This code will work with Java 14 onwards
CodePudding user response:
Without Kotlin when, Java's switch may or may not do what everything you would like. But if you do want to write with if-else, it can clean up:
if(quantity > 0){
int discount = -1
if(quantity < 4) discount = 0;
else if (quantity < 7) discount = 5;
else if (quantity < 11) discount = 10;
else discount = 15;
printDiscountMessage(discount)
}
CodePudding user response:
You can dispense with half of many of your if statements (you don't need the lower bounds check)
if (quantity <4){
System.out.print("no discount");
}
else if (quantity <7){
System.out.print(discount[1] "% discount");
}
else if (quantity <11){
System.out.print(discount[2] "% discount");
}
CodePudding user response:
use this
int discountCalculation = (quantity >= 1 && quantity < 4) ?discount[0]: (quantity >= 4 && quantity < 7)?discount[1]: (quantity >= 7 && quantity < 11) ?discount[2]:discount[3];
