【发布时间】:2020-04-30 14:11:50
【问题描述】:
所以我有一个Prodcut 类,它接受 String、String、int、Double(ID、名称、数量、成本)。
我还有一个Store 类,我保存所有方法并从控制台菜单调用它们。例如,这是我的 addProduct 方法,稍后会出现错误:
Product newProdcut(String id, String prodName, Integer prodQuantity, Double prodCost) throws Exception {
Scanner sc = new Scanner(System.in);
for ( Product p : products ) {
if ( id.equals(p.id)) {
System.out.println("Product already exists, please enter the number of the quantity you want to add to the existing quantity:");
int inputQuantity = sc.nextInt();
prodQuantity += inputQuantity;
}
}
Product p = new Product(id, prodName, prodQuantity, prodCost);
this.products.add(p);
System.out.println("Prodcut "+p.createOutput()+" was added to the list");
return p;
}
在我的菜单中,我有一个填充变量的方法,因此我可以在菜单中使用它们:
private static ArrayList<String> menuAddProdcut() throws Exception { // 1. Add a prodcut
Random rand = new Random();
System.out.println("You're adding a new prodcut");
ArrayList newProductArray = new ArrayList<>();
int prodId = rand.nextInt(1000) + 100;
String prodIdStr = Integer.toString(prodId);
System.out.println("Enter product name:");
String prodName = sc.nextLine();
System.out.println("Enter quantity:");
Integer prodQuantity = sc.nextInt();
System.out.println("Enter product's price:");
Double price = sc.nextDouble();
newProductArray.add(prodIdStr); //str-converted ID
newProductArray.add(prodName);
newProductArray.add(prodQuantity);
newProductArray.add(price);
return newProductArray;
}
这就是我从菜单中调用函数的方式:
case 1:
try {
ArrayList<String> productToPopulate = Menu.menuAddProdcut();
int quantity = Integer.parseInt(productToPopulate.get(2));
Double cost = Double.parseDouble(productToPopulate.get(3));
st.newProdcut(productToPopulate.get(0), productToPopulate.get(1), quantity, cost);
} catch (Exception e) {
e.printStackTrace();
}
break;
当我运行程序并尝试添加产品时,我收到此错误:java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader 'bootstrap')
所以我谷歌了一下,发现我应该把它转换成一个字符串,但我不能,因为该方法接受 str str int double 而不是 4 str's。
我的选择是什么?
完整的错误:
java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader 'bootstrap')
at Menu.employeeSubMenu(Menu.java:119)
at Menu.mainMenu(Menu.java:60)
at Menu.main(Menu.java:25)
【问题讨论】:
-
在堆栈跟踪中应该指向发生非法转换的行和文件。你能分享完整的错误吗?
-
这里的问题是您使用列表来保存异构数据。为什么您认为需要将这些值放在一个列表中?
-
@FedericoklezCulloca 因为我也在使用 CSV 文件,我需要能够从它们保存和导入数据。在我开始使用非字符串数据之前,它运行良好。
-
@PauMAVA 添加,谢谢
-
好的,但是如果你的问题改变了,你也需要改变你的程序。当您需要将该数据输出到 CSV 文件时,使用类对产品进行建模并在最后转换为字符串。
标签: java