-2

I'm trying to create a Stock Control Java project that reads multiple "products" from a text file, and creates "Product" objects containing the data at runtime. An example of my current data format within the text file is:

4462:Coca-Cola 2L Bottle:1.69;4980:Andrex 4 Pack:1.99;2620:Haribo Strawbs 80g:0.50;3223:Pedigree in gravy (with Chicken):0.75;

I am separating the different variables of a specific product using : and I'm separating different products using ;.

How would I go about extracting product variables and differentiating them from different products?

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
R Dev
  • 21
  • 1
  • 6

1 Answers1

1

You are on the right track. The important thing is to split twice - once for the products, and once for the individual attributes.

Firstly, create a class which defines each product. I've taken a guess at what the fields mean in this example:

class Product {
    String id;
    String name;
    String price;
}

Now you can read in the file and build instances of a product from the fields.

// Read the entire file
String text = new String(Files.readAllBytes(Paths.get("D:/input.txt")), StandardCharsets.UTF_8);

// Split into an array of strings, representing products
String[] prodStr = text.split(";");

// Create a list of product objects, currently empty
List<Product> prodList = new ArrayList<>();

// Loop over each product string
for (String pr : prodStr) {

    // Split this string into separate fields
    String[] fields = pr.split(":");

    // Build a product object from the fields
    Product product = new Product();
    product.id = fields[0];
    product.name = fields[1];
    product.price = fields[2];

    // Add this product to the list
    prodList.add(product);

}

// Print all the products to see what we get
System.out.println(prodList);

I added a toString() method to the Product class, and running this code with your example data gives:

[Product{id='4462', name='Coca-Cola 2L Bottle', price='1.69'}, Product{id='4980', name='Andrex 4 Pack', price='1.99'}, Product{id='2620', name='Haribo Strawbs 80g', price='0.50'}, Product{id='3223', name='Pedigree in gravy (with Chicken)', price='0.75'}]

To differentiate between products, implement hashCode() and equals(). e.g. A very simplistic solution could be:

@Override
public int hashCode() {
    return id.hashCode();
}

@Override
public boolean equals(Object o) {
    Product product = (Product) o;
    return id.equals(product.id);
}
starf
  • 1,063
  • 11
  • 15