Java中cartList不更新输出null?附代码及相关警告问题
问题解决方案
1. cartList打印元素为null的原因及修复
你的displayProductsFromCart方法输出null,核心问题是子类构造函数未正确初始化父类Product的属性。
假设AlcoholicBeverage和FoodProduct是Product的子类,必须在子类构造函数中调用父类构造方法,传递name、price等核心属性:
// AlcoholicBeverage示例构造函数 public class AlcoholicBeverage extends Product { private double alcoholPercentage; public AlcoholicBeverage(int id, String name, double price, int quantity, double alcoholPercentage) { // 调用父类构造初始化name、price等属性 super(id, name, price, quantity); this.alcoholPercentage = alcoholPercentage; } }
如果父类Product的getName()和getPrice()返回未初始化的成员变量,自然会输出null。
另外输入处理存在隐患:input.nextInt()读取选项后,缓冲区残留换行符,input.nextLine()会吃掉这个换行,但input.next()只能读取到第一个空格前的字符串,若产品名称包含空格(如"Apple Juice"),会导致SQL查询无结果,cartList根本没添加元素。建议改用input.nextLine()读取完整产品名称:
input.nextLine(); // 清除之前的换行符 String productName = input.nextLine(); // 读取带空格的完整名称
2. "return语句从未被使用"的修复
addProductToCart方法返回cartList,但你在main方法中调用时并未接收返回值(case 1 -> addProductToCart(input);),因此IDE提示return语句无用。
由于cartList是静态成员变量,方法内部直接修改它即可,无需返回,将方法改为void类型更合理:
private static void addProductToCart(Scanner input) throws SQLException { // 原有逻辑保留,删除最后的return cartList; }
3. "字段cartList可设为final"的处理
cartList是静态ArrayList,你仅修改集合内元素,从未重新赋值这个列表对象(比如没有cartList = new ArrayList<>();这类代码),因此可以安全添加final修饰符——这不会影响你向列表中添加/删除元素:
private static final List<Product> cartList = new ArrayList<>();
4. 其他优化建议
- 资源关闭:JDBC的
Connection、PreparedStatement、ResultSet必须关闭,否则会导致数据库连接泄漏,建议用try-with-resources自动关闭:
try (Connection connection = DriverManager.getConnection(JDBC_URL, USER, PASSWORD); PreparedStatement pStatement = connection.prepareStatement(sql)) { pStatement.setString(1, productName); try (ResultSet resultSet = pStatement.executeQuery()) { while(resultSet.next()) { // 处理结果集逻辑 } } }
- 循环选择:当前
main方法中用户选择后程序直接结束,添加循环让用户可重复操作:
Scanner input = new Scanner(System.in); int choice; do { System.out.println("1. 添加商品到购物车"); System.out.println("2. 查看购物车"); System.out.println("3. 退出"); choice = input.nextInt(); switch(choice){ case 1 -> addProductToCart(input); case 2 -> displayProductsFromCart(); case 3 -> System.out.println("退出程序"); default -> System.out.println("无效选项"); } } while (choice != 3);
内容的提问来源于stack exchange,提问作者Raduci
相关产品推荐
相关产品推荐

