以下是解题思路和代码实现:\n\n解题思路:\n1) 在ShoppingCart类中,定义一个静态方法calculateTotalPrice,该方法接收一个字符串数组items和一个双精度浮点数数组prices作为参数。\n2) 首先,判断items和prices数组的长度是否相等,如果不相等,则抛出一个IllegalArgumentException异常。\n3) 然后,使用一个循环遍历items数组和prices数组,将每个商品的价格累加到一个变量totalPrice中。\n4) 最后,返回计算得到的totalPrice。\n5) 在主类Prog1的main方法中,使用Scanner类从控制台读取用户输入的商品数量itemCount。\n6) 创建一个长度为itemCount的字符串数组items和一个长度为itemCount的双精度浮点数数组prices。\n7) 使用一个循环依次从控制台读取每个商品的名称和价格,并将其分别存储到items数组和prices数组中。\n8) 调用ShoppingCart类中的calculateTotalPrice方法,传入items数组和prices数组,计算商品总价totalPrice。\n9) 将商品总价totalPrice输出到控制台上。\n\n代码实现:\n\nimport java.util.Scanner;\n\npublic class Prog1 {\n public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n \n System.out.print("请输入购物车中商品的数量:");\n int itemCount = scanner.nextInt();\n scanner.nextLine(); // 读取换行符\n \n String[] items = new String[itemCount];\n double[] prices = new double[itemCount];\n \n for (int i = 0; i < itemCount; i++) {\n System.out.print("请输入第" + (i + 1) + "个商品的名称:");\n items[i] = scanner.nextLine();\n \n System.out.print("请输入" + items[i] + "的价格:");\n prices[i] = scanner.nextDouble();\n scanner.nextLine(); // 读取换行符\n }\n \n double totalPrice = ShoppingCart.calculateTotalPrice(items, prices);\n System.out.println("购物车中商品的总价为:" + totalPrice + "元");\n }\n}\n\nclass ShoppingCart {\n public static double calculateTotalPrice(String[] items, double[] prices) {\n if (items.length != prices.length) {\n throw new IllegalArgumentException("商品名称和价格数组长度不一致");\n }\n \n double totalPrice = 0.0;\n \n for (int i = 0; i < items.length; i++) {\n totalPrice += prices[i];\n }\n \n return totalPrice;\n }\n}

Java购物车商品总价计算程序 - 优化代码实现

原文地址: https://www.cveoy.top/t/topic/pGRn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录