使用switch语句对用户输入进行分类记录。
代码如下:
//Java how to program, 10th edtion
//Exercise 5.17, Calculating Sales
/**(Calculating Sales) An online retailer sells five products whose retail prices are as follows:
Product 1, $2.98; product 2, $4.50; product 3, $9.98; product 4, $4.49 and product 5, $6.87.
Write an application that reads a series of pairs of numbers as follows:
a) product number
b) quantity sold
Your program should use a switch statement to determine the retail price for each product. It
should calculate and display the total retail value of all products sold. Use a sentinel-controlled
loop to determine when the program should stop looping and display the final results.*/
import java.util.Scanner;
public class SalesCalc {
public static void main(String[] args){
Scanner input=new Scanner(System.in);
int[] quantity=new int[5];
int productNumber=0;
double sales=0.0;
while(productNumber!=-1){
System.out.print("请输入产品号码:");
productNumber=input.nextInt();
switch(productNumber){
case 21001:
quantity[0]++;
break;
case 21002:
quantity[1]++;
break;
case 21003:
quantity[2]++;
break;
case 21004:
quantity[3]++;
break;
case 21005:
quantity[4]++;
break;
default:
}
}
sales=quantity[0]*2.98+quantity[1]*4.5+quantity[2]*9.98+
quantity[3]*4.49+quantity[4]*6.87;
System.out.printf("本单销售金额为:%.2f\n",sales);
}
}
运行结果:
请输入产品号码:21001
请输入产品号码:21002
请输入产品号码:21001
请输入产品号码:21005
请输入产品号码:21004
请输入产品号码:21003
请输入产品号码:21002
请输入产品号码:21005
请输入产品号码:21000
请输入产品号码:-1
本单销售金额为:43.17