First, indicate to User the products available and their respective price:
int productChoice = 0;
int quantity = 0;
double totalSum = 0.0;
System.out.println("Welcome To The Mail_Order House.");
System.out.println("Please select Product Number (1 to 5) you want to buy:\n");
System.out.println("1) Product Name 1: RM2.98");
System.out.println("2) Product Name 2: RM4.50");
System.out.println("3) Product Name 3: RM9.98");
System.out.println("4) Product Name 4: RM4.49");
System.out.println("5) Product Name 5: RM6.87");
This allows the User to easily see what is available to buy and therefore make a valid choice. Now ask the User to enter a product number:
productChoice = sc.nextInt();
The value the User supplies relates to the product name he/she wants. Now it’s just a matter of asking the User the desired quantity of that specific product:
System.out.println("What quantity of Product #" + productChoice + " do you want?");
quantity = sc.nextInt();
Now that we have the product quantity it’s a matter using IF/ELSE IF to gather the price of that selected product and multiply it by the User supplied quantity to achieve the total sum owed for that product:
if (productChoice == 1) {
// ......TO DO........
}
else if (productChoice == 2) {
totalSum += 4.50 * quantity;
// This is the same as: totalSum = totalSum + (4.50 * quantity);
}
else if (productChoice == 3) {
// ......TO DO........
}
else if (productChoice == 4) {
// ......TO DO........
}
else if (productChoice == 5) {
// ......TO DO........
}
else {
System.out.println("Invalid product number supplied!");
}
As you can see, you now have all the required data to display the required output String to Console:
System.out.println("Mail-Order House sold " + quantity +
" of Product #" + productChoice + " for: RM" +
String.format("%.2f", totalSum));
The String.format("%.2f", totalSum)
in the above line ensures a precision of 2 decimal places in the total sum is displayed to console. You wouldn’t want a number like: 21.422000522340
to be displayed as a monetary value in this particular case (read up on the String.format() method).
1
solved Using java if-else [closed]