Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read data from a text file and create an object

I need some help: I'm making a Supermarket simulation on Java, but I've got one problem, I have a text file (Stock.txt) where I have all the supermarket stock on it for example:

  • 0-Bakery-Chocolate Cake-$12.5-250
  • 1-Meat-Premium Steak-$2.6-120
  • 2-Seafood-Tuna - $1.2-14
  • ...

Where the first number is the "id" for the product, next is the department the product belongs, third is the name of the product, the next thing is the price, and the last number is how much pieces of the product the stock has. I have this class:

public class Product {
    protected String name;
    protected double price;
    protected String department;
    protected int id;
    protected int stock;
}

So, basically what I need to do is to read each line from the text file and create the product, i.e. for the first line make something like this:

Product product1 = new Product(0,"Bakery","Chocolate Cake", 12.5, 250);     

And then add it to an array

Product[0] = product1;

For all the things that are in the text file, then, when running the simulation each costumer will buy a random quantity of random products in stock, so the stock number will decrease. Finally, when the simulation ends, the program must write in the same text file, the modify quantity of each product.

The thing is that maybe it's too easy to do but I have no idea of how to do this, because reading and writing a file in Java has been a real problem for me since I started programming in Java (I'm a beginner). I have some ideas of using the BufferedReader and the StringTokenizer classes for the reading and creating the object problems, but I can't figure it out how to do it, and I have no idea of how must I do the overwritting problem. I'd really appreciate your help!

Oh! By the way, I really need to use only the arrays, so using an ArrayList or any other structure it's not even a choice :(

like image 283
DkRckr12 Avatar asked Dec 25 '22 18:12

DkRckr12


2 Answers

This is a good job for a Scanner to read in the data. As far as not being able to use collections like ArrayList you'll have to dynamically reallocate an array yourself.

Try the following:

public static void main(String[] args) throws FileNotFoundException {
    Scanner input = new Scanner(new File("Stock.txt"));
    input.useDelimiter("-|\n");

    Product[] products = new Product[0];
    while(input.hasNext()) {
        int id = input.nextInt();
        String department = input.next();
        String name = input.next();
        double price = Double.valueOf(input.next().substring(1));
        int stock = input.nextInt();

        Product newProduct = new Product(name, price, department, id, stock);
        products = addProduct(products, newProduct);
    }

    for (Product product : products) {
        System.out.println(product);
    }
}

private static Product[] addProduct(Product[] products, Product productToAdd) {
    Product[] newProducts = new Product[products.length + 1];
    System.arraycopy(products, 0, newProducts, 0, products.length);
    newProducts[newProducts.length - 1] = productToAdd;

    return newProducts;
}

public static class Product {
    protected String name;
    protected double price;
    protected String department;
    protected int id;
    protected int stock;

    private static NumberFormat formatter = new DecimalFormat("#0.00");

    public Product(String n, double p, String d, int i, int s) {
        name = n;
        price = p;
        department = d;
        id = i;
        stock = s;
    }

    @Override
    public String toString() {
        return String.format("ID: %d\r\nDepartment: %s\r\nName: %s\r\nPrice: %s\r\nStock: %d\r\n", 
                id, department, name, formatter.format(price), stock);
    }
}

Results:

ID: 0
Department: Bakery
Name: Chocolate Cake
Price: 12.50
Stock: 250

ID: 1
Department: Meat
Name: Premium Steak
Price: 2.60
Stock: 120

ID: 2
Department: Seafood
Name: Tuna
Price: 1.20
Stock: 14
like image 106
Shar1er80 Avatar answered Dec 27 '22 08:12

Shar1er80


For simplicity, I have defined all the items as String.

Product DAO:

public class Product {

    private String name;
    private String price;
    private String department;
    private String id;
    private String stock;

    //generate `enter code here`
    //getters & setters
    //toString

Put your product list in "testData/product.txt". This is assuming that your list of products comes in same format, i.e. id-department-name-price-stock \n.

Use the jUnit test below to test your code. You can certainly modify how you read the product.txt file (may be other powerful string readers).

@Test
    public void test() {

        try {
            List<String> productLines = Files.readAllLines(java.nio.file.Paths.get("./testData/product.txt"), StandardCharsets.UTF_8);

            for (String line: productLines)
Product product = new Product();
                String[] tokens = line.split("-");

                product.setId(tokens[0]);
                product.setDepartment(tokens[1]);
                product.setName(tokens[2]);
                product.setPrice(tokens[3]);
                product.setStock(tokens[4]);

System.out.println(product.toString())
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    } 
like image 42
gkc123 Avatar answered Dec 27 '22 06:12

gkc123