Home > other >  How to create an inventory, add each sale in a dynamic array and calculate total income
How to create an inventory, add each sale in a dynamic array and calculate total income

Time:08-16

I'm new in Java and I have to create an inventory program. The program is: "A salesman enters his sales in a text file. Every line contains the following (separated by a semicolon; ):

  • Name of customer (only letters and spaces allowed)
  • Device sold (smartphone, tablet or laptop)
  • price (like this ####,##)
  • date of sale (dd/mm/yy ex. 21/03/21)

Then create a program that does the following: -Reads from the user the name of the file and opens it. Use the proper exception for the case of the file not existing and ask the user to enter the name of the file again

-Create a class named "Sale" which can store in each of its objects a sale (name, device, price and date, like above). For the device type use ENUM, for the date create a class named "LocalDate"

-Reads the data from the text file and puts them in a dynamic array of 'Sale' objects

-Calculates and prints the total income from the sales for each device type "

So far I have this:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.ArrayList;

public class Files {
    public static void main(String[] args)  {
        Scanner in = new Scanner(System.in);
        System.out.println("What is the filename?");
        String input = in.nextLine();
        File file = new File(input);


        if(file.exists()){
            System.out.println("The file exists. ");
        }else {
            File file2;
            do {
                System.out.println("That file does not exist. Please enter the name again. ");
                Scanner in2 = new Scanner(System.in);
                String input2 = in2.nextLine();
                file2 = new File(input2);
                if (file2.exists()) {
                    System.out.println("The file exists. ");
                }
            } while (!file.exists() && !file2.exists());
        }

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

        try(BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\Katerina Efstathiou\\Desktop\\JAVA (1) - Files and exceptions\\javaprogrone.txt"))){
            String line;

            while ((line = br.readLine()) != null)
                //Add the line to the array-list:
                sales.add(line);

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

        int listSize = sales.size();  //variable with the size of the list 'sales'

        String[] listOfPrices = new String[listSize];  //define an array of the size of the list

    }
}

The 'Sale' class:

public class Sale {
    private String customerName;  //variables are declared as private

    //enum class DeviceType - (enum classes represent a group of constants, like final variables)
    //Enum is short for "enumerations", which means "specifically listed"
    enum DeviceType{
        SMARTPHONE,
        TABLET,
        LAPTOP
    }

    private double price;  //variables are declared as private

    public Sale(String firstName, String lastName){  //constructor of Sale class
        customerName = firstName " " lastName;
        price = 0.0;
    }

    //subclass LocalDate is static ,so I can access it without creating an object of the Sale class
    static class LocalDate{
        private int Day;
        private int Month;
        private int Year;

        LocalDate(){
            Day=0;
            Month=0;
            Year=0;
        }

        public void Date(){
            System.out.println(Day "/" Month "/" Year);
        }

    }
}

And this is the file that I made:

file of sales

So my issue is how to add each object in an array and how do I calculate the income from the sales for each device? (Meaning if I sold 4 smartphones, how much is the total income for these 4 smartphones?).

I'm really desperate...I don't know what else to do and I really need help...

CodePudding user response:

Understanding that you're learning Java, I've tried to be as simple as possible and have updated your code and pointed out the mistakes.

Let's move step by step.

1: Segregating components

DeviceType enum and LocalDate class

public enum DeviceType {
        SMARTPHONE,
        TABLET,
        LAPTOP;
    }
public class LocalDate {
        private int day;
        private int month;
        private int year;

        public static LocalDate date(String date) {
            final String[] path = date.split("/");
            final LocalDate result = new LocalDate();
            result.day = Integer.parseInt(path[0]);
            result.month = Integer.parseInt(path[1]);
            result.year = Integer.parseInt(path[2]);
            return result;
        }
    }

Notice how I've made seperate enum for DeviceType (instead of a sub-enum). In our Sale class we will just use hasA relationship for the above components.

Also, in the date method, I've updated the logic where you can return an instance of LocalDate class based on your input.

2: Using components

public class Sale {
        private final String customerName;
        private final double price;
        private final DeviceType deviceType;
        private final LocalDate date;

        public Sale(String firstName, String lastName, final String device, final String cost, final String date) {  //constructor of Sale class
            customerName = firstName   " "   lastName;
            price = Double.parseDouble(cost);
            deviceType = DeviceType.valueOf(device);
            this.date = LocalDate.date(date);
        }

        public DeviceType getDeviceType() {
            return deviceType;
        }
        
        public double getPrice() {
            return price;
        }

        public LocalDate getDate() {
            return date;
        }

        public String getCustomerName() {
            return customerName;
        }
    }

In this step, we construct our Sale class using the inputs provided to us. We will make use of the components we created above.

3: Getting result

List<Sale> sales = new ArrayList<>();

        try (BufferedReader br = new BufferedReader(new FileReader(file.getAbsolutePath()))) {
            String line;

            while ((line = br.readLine()) != null) {
                //Add the line to the array-list:
                final String[] parts = line.split(";");
                final String[] cost = parts[2].split(",");
                final String[] names = parts[0].split(" ");
                final String firstName = names[0].trim();
                final String lastName = names[1].trim();
                final String costInteger = cost[0].trim();
                final String costDecimal = cost[1].trim();
                final String device = parts[1].trim();
                final String date = parts[3].trim();
                final Sale sale = new Sale(firstName, lastName, device, costInteger   "."   costDecimal, date);
                sales.add(sale);
            }

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

        final DeviceType[] deviceTypes = DeviceType.values();
        for (final DeviceType deviceType : deviceTypes) {
            double sum = 0;
            for (final Sale sale : sales) {
                if (sale.getDeviceType().name().equals(deviceType.name())) {
                    sum  = sale.getPrice();
                }
            }
            System.out.println("Income for device "   deviceType.name()   " is "   sum);
        }

instead of creating ArrayList sales = new ArrayList<>(); we should create a List of Sale

and also for reading the name of file use the file object you created above in your code.

Once, we all things set-up we will just try to find the sum for all the available DeviceType present in the sales list.

CodePudding user response:

First of all you have to modify constructor, it should takes arguments if we want to create objects and add them to list base on file data, it should look like this:

public Sale(String name, double price){  //constructor of Sale class
                customerName = name;
                this.price = price;
       }

Then the main method should looks like:
    public class Files {
        public static void main(String[] args)  {
    
    
        ArrayList<String> sales = new ArrayList<>();
        
                try(BufferedReader br = new BufferedReader(new FileReader(/*here put your file path"/Users/aabdelaziz/Desktop/f.txt"))){
                    String line;
        
                    while ((line = br.readLine()) != null)
                        //Add the line to the array-list:
                        sales.add(line);
        
                }catch(IOException e){
                    e.printStackTrace();
                }
        
                ArrayList<Sale> listOfSales = new ArrayList<>();
                //add sales objects from file to list of sales
                for (String s: sales){
                    String[] saleProperties = s.split(";");
                    //switch the comma in price number by dot
                    String[] splitPrice = saleProperties[2].split(",");
                    double price = Double.parseDouble(splitPrice[0]   "."   splitPrice[1]);
                    Sale sale = new Sale(saleProperties[0].trim(),  price);
                    listOfSales.add(sale);
                }
                //calculate total prices
                double totalPrices = 0;
                for (Sale sale: listOfSales){
        //you have to add getPrice Method in Sale class
                    totalPrices  = sale.getPrice();
                }
                System.out.println(totalPrices);
        }
    }

//if you interested in date and device type you can add them in constructorenter code here

  • Related