java - 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++;
}
解决方案
因此,如果您有一个代表产品信息的字符串:
String productInfo = "product;info;here";
您可以Product
通过将其传递给Product
构造函数将其转换为:
Product product = new Product(productInfo);
所以原来的行
products[curNumOfProducts - 1] = productLine;
变成
products[curNumOfProducts - 1] = new Product(productLine);
推荐阅读
- python-3.x - 如何从熊猫数据框中的列中删除不需要的文本
- c# - c# wpf treeviewitem with contextmenu
- python - 如何使用 scipy.ndimage.interpolate 在 3d 中随机旋转 numpy 数组?
- c# - 如何在 mvc 中访问 _layout.cshtml 中的单个视图?
- bash - 从 /etc/rc.local 运行的脚本问题
- amazon-web-services - moto cognito sign_up 功能不起作用
- python - 在 python-pptx 中使用循环创建多张幻灯片并将数据帧写入幻灯片
- angular7 - 调试 Angular 代码时无法在 Google Chrome 中查看变量值
- php - 为什么我不能通过 php cURL 抓取远程站点数据?
- django - 如何从 django 中与外键链接的所有 id 中提取所有对象?