如何找到修复运行时int强制转换错误的方法



所以我有一个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')

所以我在谷歌上搜索了一下,发现我应该将它强制转换为String,但我不能,因为该方法接受str-str-int double,而不是4 str。

我在这里有什么选择?

完整错误:

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)

问题是由以下行引起的:

ArrayList newProductArray = new ArrayList<>(); 

将变量定义为原始类型ArrayList(原始类型是指没有为需要的类型指定类型参数的情况(。应不惜一切代价避免使用原始类型。

在这种情况下,它会导致menuAddProdcut方法返回一个包含非Strings的对象的ArrayList<String>!这在全类型系统中是不可能的,只有当原始类型破坏了类型系统时才会发生(还记得我告诉你要避免它们吗?(

将代码更改为

ArrayList<String> newProductArray = new ArrayList<>(); 

然后编译器会告诉你这些行不起作用:

newProductArray.add(prodQuantity);
newProductArray.add(price);

因为您试图将IntegerDouble分别添加到ArrayList<String>。将它们更改为类似的内容

newProductArray.add(prodQuantity.toString());
newProductArray.add(price.toString());

最新更新