首页 > 解决方案 > change type of object into type I created in java

问题描述

I'm managing a grocery list in a main class called shoppingList, and I created a new class named Product to handle the String (I get a string full of data on the product and in the class Product I use the .split(";") and arrays to arrange the data as needed.

On the main class - shoppingList - there is a method called addProduct that I need to execute, and this method get a String. How do I change this String to be type Product so I can add this product into an array of products (products[currentNumOfProducts-1] = productLine)?

Thanks in advance!

public class Product {
    private String type;
    private double price;
    private int id;
    private String manifactor;
    private ExtraData extraData;

    public Product(String item) {
        String[] parts = item.split(",");
        type = parts[0];
        type = parts[1];
        switch (type) {
            case "ElectricProduct":
                extraData = new ElctricExtraData(item);
                break;
            case "Book":
                extraData = new BookExtraData(item);
                break;
        ...

This is the class Product -and the method on Shopping list:

public void addProduct (String productLine){
                if (curNumOfProducts < products.length) {
                    products[curNumOfProducts - 1] = productLine;
                    curNumOfProducts++;
                }

标签: java

解决方案


因此,如果您有一个代表产品信息的字符串:

String productInfo = "product;info;here";

您可以Product通过将其传递给Product构造函数将其转换为:

Product product = new Product(productInfo); 

所以原来的行

 products[curNumOfProducts - 1] = productLine;

变成

 products[curNumOfProducts - 1] = new Product(productLine); 

推荐阅读