Java向Shop类ArrayList添加Product对象后输出为空的问题排查
错误原因汇总
Shop类的addToList方法逻辑错误:方法内部新创建了空的Product对象添加到集合,没有使用传入的已赋值的Product实例,导致集合中存储的都是无数据的空对象- 方法传参类型不匹配:
addToList要求传入Product类型参数,主方法调用时传入了String类型的a.Code,触发类型错误 - 命名不统一问题:实例化的
Shop对象变量名为shop,调用时写成了tienda;Product类的获取价格方法名为getPrice,调用时错写为getPice;Shop类的店铺名称静态变量名为nombre,主方法调用时错写为Tienda.name Scanner输入逻辑错误:getPrice方法中Price是double类型,却使用nextInt()接收输入;调用nextInt()后未处理残留的换行符,会导致后续nextLine()读取到空值- 打印集合无有效内容:
Product类未重写toString()方法,即使对象正确存入集合,打印时也只会输出对象内存地址 switch分支缺少break:case 1分支执行完后没有加break,会直接穿透到default分支
修复后的代码
Shop类
import java.util.ArrayList; import java.util.Scanner; public class Shop { Scanner sn = new Scanner(System.in); // 集合类型改为Product更安全,无需使用Object static ArrayList<Product> list = new ArrayList<>(); public static String nombre = "Shop"; public Shop(String name) { System.out.println(name); } public Shop() { } // 修改为添加传入的已赋值Product对象 public void addToList(Product a) { list.add(a); } public void searchProduct(String code) { } public void order(int min) { } }
Product类
import java.util.Scanner; public class Product { Scanner sn = new Scanner(System.in); String code; int quantity; double price; public String getCode() { System.out.println("Please introduce the code of the product"); // 先处理可能残留的换行符 if (sn.hasNextLine()) { sn.nextLine(); } code = sn.nextLine(); return code; } public int getQuantity() { System.out.println("Please introduce the quantity of the product"); quantity = sn.nextInt(); return quantity; } public double getPrice() { System.out.println("Please introduce the price for the product"); // 改为nextDouble接收double类型输入 price = sn.nextDouble(); return price; } // 重写toString方法,打印时输出属性内容 @Override public String toString() { return "Product{" + "code='" + code + '\'' + ", quantity=" + quantity + ", price=" + price + '}'; } }
主方法类
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sn = new Scanner(System.in); // 修正店铺名称调用 System.out.println("Welcome to "+ Shop.nombre +" .What do you wanna do?\n1.Add new product\n2.Sell product"); Product a = new Product(); Shop shop = new Shop(); int opt = sn.nextInt(); switch(opt){ case 1: System.out.println("You choose add a Product"); a.getCode(); a.getQuantity(); // 修正方法名拼写 a.getPrice(); // 修正调用对象、传参为整个Product对象 shop.addToList(a); System.out.println("The code for the product is: "+a.code+ "\nThe quantity of the product is: "+ a.quantity+ " units"+ "\nThe price for the product is: "+ a.price+ "$"); // 打印集合验证结果 System.out.println(Shop.list); // 增加break防止分支穿透 break; case 2: // 后续业务逻辑自行补充 break; default: System.out.println("Wrong option"); break; } } }
内容的提问来源于stack exchange,提问作者Martín
相关产品推荐
相关产品推荐

