//使用java编写简单的商城购物流程
package shopping;
import java.util.Scanner;
/**
* 1.用户输入商品编号和数量进行购物,如果商品编号不存在,用户可以选择是否继续购物
* 2.购物过程中,用户每完成一次购物选择,输出相应的购物信息(该商品的单价、购买数量、本次合计金额)
* 3.当用户结束购物时,进行支付操作
* 4.用户输入折扣和实付金额,直到实付金额大于应付金额,才输出完整的购物清单
*/
public class Shopping {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("***************************************");
System.out.println("请选择购买的商品编号:");
System.out.println("1.T恤 2.网球鞋 3.网球拍");
System.out.println("***************************************");
//计算所有商品的总金额
double totalMoney = chooseGood();
while (isContinueBuy()) {//继续购物,继续累计购物金额
totalMoney = totalMoney + chooseGood();
}
//结束购物,输出购物清单
shoppingList(totalMoney);
}
//输入折扣和实付金额,如果实付金额足够,则输出购物清单
private static void shoppingList(double totalMoney) {
System.out.print("折扣:");
double discount = scanner.nextDouble();
double needPay = totalMoney - discount;
System.out.println("应付金额: " + needPay);
System.out.print("实付金额:");
double realPay = scanner.nextDouble();
while (needPay > realPay) {
System.out.print("您输入的金额小于应付金额,请重新输入:");
realPay = scanner.nextDouble();
}
double rebackMoney = realPay - needPay;
System.out.print("找钱:" + rebackMoney);
}
//判断用户是否继续购物,返回布尔型数据(true、false)
private static boolean isContinueBuy() {
System.out.print("是否继续(y/n) ");
String isContinueBuy = scanner.next();
System.out.println();
if ("y".equals(isContinueBuy) || "Y".equals(isContinueBuy)) {//等于y或者Y
return true;
}else if ("n".equals(isContinueBuy) || "N".equals(isContinueBuy)){ //等于n或者N
return false;
}
System.out.println("输入格式有误,正确格式y-Y-n-N");
return isContinueBuy();
}
//选择商品,输入购买数量,统计购买该商品的总金额
private static double chooseGood() {
System.out.print("请输入商品编号:");
int id = scanner.nextInt();
System.out.print("请输入购买数量:");
int num = scanner.nextInt();
double price = 0; //单价
double goodMoney = 0; //合计价格
switch (id) {
case 1:
price = 245.0;
goodMoney = price * num;
System.out.println(String.format("T恤¥%s\t数量 %s 合计 ¥%s", price, num, goodMoney));
break;
case 2:
price = 570.0;
goodMoney = price * num;
System.out.println(String.format("T恤¥%s\t数量 %s 合计 ¥%s", price, num, goodMoney));
break;
case 3:
price = 320.0;
goodMoney = price * num;
System.out.println(String.format("T恤¥%s\t数量 %s 合计 ¥%s", price, num, goodMoney));
break;
default:
System.out.println("**************商品编号" + id + "不存在**************");
break;
}
return goodMoney;
}
}
效果图