实验 2-4 编写程序,模拟购物。

实验 2-4 编写程序,模拟购物。

(1) 输入商品名称、单价、数量,计算商品价格,输出商品名称,单价,数量,总价。

(2) 当总价大于或等于500时,享受8折优惠。

(3) 模拟付款找零过程。

(4) 若付款金额不足,需要继续付款。

(5) 购买多件商品时,需要对多件商品的总价进行汇总,得到应付款额,请程序中实现。
方法二

import java.util.Scanner;
public class ship{
    String name = null;
    int num = 0;
    double price = 0;
   public static void main(String[] args){
   int a = 0;
  double money = 0;
  Scanner sc = new Scanner(System.in);
  System.out.println("输入‘*’继续,输入‘#’结束。");
  System.out.println("*********************************");
        ship pp[] = new ship[10];

        pp[0] = new ship();
    System.out.print("商品:");
    pp[0].name = sc.next();
    System.out.print("单价:");
    pp[0].price = sc.nextDouble();
    System.out.print("数量:");
    pp[0].num = sc.nextInt(); 
    money = pp[a].price * pp[a].num;
    
    
   while(true) {
  System.out.print("输入‘*’继续,输入‘#’结束。请输入:");
  String st = sc.next();
  
  char A = st.charAt(0);
  switch(A) {
  case '*':
   a++;
   pp[a] = new ship();
   System.out.print("商品:");
   pp[a].name = sc.next();
   System.out.print("单价:");
   pp[a].price = sc.nextDouble();
   System.out.print("数量:");
   pp[a].num = sc.nextInt(); 
   money += pp[a].price * pp[a].num;
   //System.out.println("a=" + a);
   break;
   case '#':
   System.out.println("*********************************");
   System.out.println("\t\t  小票");
   System.out.println("-------------------------------------------------");
   System.out.println("商品\t\t单价\t\t数量");
   for(int i = 0; i <= a;i++) {
    System.out.println(pp[i].name+"\t\t"+pp[i].price+"\t\t"+pp[i].num);
   }
   System.out.println("-------------------------------------------------");
   if(money >= 800) {
    money = money * 0.8;
   }
   
   System.out.println("总金额为:" + money);
   System.out.print("请付款:");
   double pmoney = sc.nextDouble();
   if(pmoney > money) {
       System.out.println("找您:" + (pmoney - money) + "元" );
       System.out.println("感谢您的惠顾!");
       return;
        }
      
      
      if (pmoney == money)
      {
       System.out.println("感谢您的惠顾!");
       return;
      }
      
      if(pmoney < money) {
     double F = money - pmoney;
        while(F > 0) {
         System.out.println("您还需支付:" + String.format("%.2f",F) + "元");
       System.out.print("请付款:");
       pmoney = sc.nextDouble();
       F -= pmoney;
       if(F < 0) {
        System.out.println("找您:" + String.format("%.2f", -1 * F) + "元" );
        System.out.println("感谢您的惠顾!");
        return;
       }
        } 
            }
      return;
      }
   
    } 
   
  }
 }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值