code:
//需求:循环输出商品编号和购买数量,当输出n时结账,结账时计算应付金额并找零import java.util.Scanner;public class test1 { public static void main(String[] args) { // 定义变量 Scanner sc = new Scanner(System.in); char judge; double sum = 0; double collect; String prodName1 = "T恤"; String prodName2 = "网球鞋"; String prodName3 = "网球拍"; double prodPrice1 = 245.0; double prodPrice2 = 570.0; double prodPrice3 = 320.0; // 界面 System.out.println("请选择购买的商品编号:"); System.out.println("================商品清单================"); System.out.println("1、" + prodName1 + "t" + "2、" + prodName2 + "t" + "3、" + prodName3); System.out.println("=======================================" + "n"); // 购物输入 do { System.out.println("请输入商品编号:"); int i = sc.nextInt(); System.out.println("请输入购买数量:"); int j = sc.nextInt(); switch (i) { case 1: System.out.println("T恤¥245 " + "数量 " + j + " 合计 ¥" + 245.0 * j); sum += 245.0 * j; break; case 2: System.out.println("网球鞋¥570 " + "数量 " + j + " 合计 ¥" + 570.0 * j); sum += 570.0 * j; break; case 3: System.out.println("网球拍¥320 " + "数量 " + j + " 合计 ¥" + 320.0 * j); sum += 320.0 * j; break; default: System.out.println("输入的商品编号有误,无此商品"); } System.out.println("是否继续(y/n)"); judge = sc.next().charAt(0); System.out.println(" "); } while (judge == 'y'); // 购物模块结束 // 进入计算模块 if (judge == 'n') { // 折扣计算部分 Double sale = 1.0; if (sum > 3000) { sale = 0.7; } else if (sum > 2000) { sale = 0.8; } else if (sum > 1000) { sale = 0.9; } // 输出界面 System.out.println("折扣: " + sale); System.out.println("应付金额: " + sum * sale); System.out.println("实付金额: "); collect = sc.nextDouble(); while (collect < (sum * sale)) { System.out.println("您输入的金额小于应付金额,请重新输入: "); collect = sc.nextDouble(); } System.out.println(" "); System.out.println("找钱: " + (collect - sum * sale)); double point = (sum * sale / 100) * 3; System.out.println("恭喜您获得积分:" + String.format("%.1f", point)); System.out.println("欢迎下次光临本店"); } }}
**
心得:
1、添加适当的注释,代码块的工整很重要
2、System.out.println会自动切换到下一行 不需要n**
**
不足:没有实现scanner和println在同一行,即没有实现商品数量编号的输入和文字在同一行**