Answer:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
//Initialize the prices as constants
final double PRODUCT_1_PRICE = 2.98;
final double PRODUCT_2_PRICE = 4.50;
final double PRODUCT_3_PRICE = 9.98;
final double PRODUCT_4_PRICE = 4.49;
final double PRODUCT_5_PRICE = 6.87;
//Declare the other variables
int productNumber, quantitySold;
double total = 0.0;
//Create a Scanner object to get input
Scanner input = new Scanner(System.in);
//Create a while loop
while(true){
//Ask the user to enter the productNumber
System.out.print("Enter the product number or 999 to quit: ");
productNumber = input.nextInt();
// Stop the loop, if productNumber is 999(sentinel value, you may choose any value you want)
if(productNumber == 999)
break;
//Ask the user to enter the quantitySold
System.out.print("Enter the quantity sold: ");
quantitySold = input.nextInt();
//Create a switch statement that works depending on the productNumber entered.
//For example, if the productNumber is 1, it multiplies the quantitySold by PRODUCT_1_PRICE
// and adds the result to the total. If productNumber is 2, it does the same for product 2 ...
switch(productNumber){
case 1:
total += quantitySold * PRODUCT_1_PRICE;
break;
case 2:
total += quantitySold * PRODUCT_2_PRICE;
break;
case 3:
total += quantitySold * PRODUCT_3_PRICE;
break;
case 4:
total += quantitySold * PRODUCT_4_PRICE;
break;
case 5:
total += quantitySold * PRODUCT_5_PRICE;
break;
}
}
//Print the total (when the loop is done)
System.out.println("The total is $" + total);
}
}
Step-by-step explanation:
*The code is in Java.
You may see the explanation as comments in the code.