【问题标题】:How do I find a fix for my runtime int casting error?如何找到运行时 int 转换错误的修复程序?
【发布时间】: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


【解决方案1】:

问题是由这一行引起的:

ArrayList newProductArray = new ArrayList<>(); 

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

在这种情况下,它会导致menuAddProdcut 方法返回一个ArrayList&lt;String&gt;,其中包含不是Strings 的对象!这在完整的类型系统中是不可能的,并且只会因为原始类型破坏了类型系统而发生(还记得我告诉过你要避免它们吗?)

把代码改成

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

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

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

因为您尝试将Integer 和Double 分别添加到ArrayList&lt;String&gt;。将它们更改为类似

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

【讨论】:

  • 他还得把sc.nextInt()改成sc.nextLine()。
  • @PauMAVA:不,不一定,他可能仍想向 Scanner 询问一个 int 值,以确保用户实际输入了一个数字。
  • @JoachimSauer 你是救世主!非常非常感谢!
猜你喜欢
  • 2015-10-31
  • 2019-11-14
  • 2019-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 2021-01-20
相关资源
最近更新 更多