0

When I successfully register for a customer, this customer can only order the food, how can I save the order of this customer in array? Is it using super class but it cannot work. And also I have to display all the past order of the customer.

Customer class

public class Customer {
    protected String name;
    protected String id;
    protected String home;
    protected String email;
    protected String orderDate;
    protected double amountPaid;
    protected int restaurantName;
    
    public Customer(String a, String b, String c, String d){
        name = a;
        id = b;
        home = c;
        email = d;              
    }

    public String getName(){
        return name;
    }
    
    public String getID(){
        return id;
    }
    
    public String getHome(){
        return home;
    }
    
    public String getEmail(){
        return email;
    }
    
    public String getOrderDate(){
        return orderDate;
    }
    
    public double getAmountPaid(){
        return amountPaid;
    }
    
    public int getRestaurantName(){
        return restaurantName;
    }
}
final int MAX = 100;
int customerCount = 0;
Customer[] customerList = new Customer[MAX];

This is how I define the array of object Customer

Order class

public class Order extends Customer{
    int restaurant;
    String order;
    double amount;
     String orderDate;
     double amountPaid;
     int restaurantName;
    
    public Order(String a, String b, String c, String d, int e, String f, double g){
        super(a,b,c,d);
        e = restaurant;
        f = order;
        g = amount;
    }
    
    public int getRestaurant(){
        return restaurant;
    }
    
    public String getOrder(){
        return order;
    }
    
    public double getAmount(){
        return amount;
    }
}

Register button

private void registerBTNActionPerformed(java.awt.event.ActionEvent evt) {     
String name = "", id1 = "", home = "", email = "";
        try {
            name = nameTF.getText();
            if (name.equals("")) {
                throw new IllegalArgumentException("You must specify Customer name!");
            }
            id1 = idTF1.getText();
            if (id1.equals("")) {
                throw new IllegalArgumentException("You must specify Customer ID!");
            }
            home = homeTF.getText();
            if (home.equals("")) {
                throw new IllegalArgumentException("You must specify Customer home address!");
            }
            email = emailTF.getText();
            if (email.equals("")) {
                throw new IllegalArgumentException("You must specify Customer email address!");
            }
            for (int i = 0; i < customerCount; i++) {
                if (id1.equals(customerList[i].getID())) {
                    outputTA.setText("The customer ID is registered before!");
                    idTF1.setText("");
                    return;
                }
            }
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "Illegal Customer Name or Customer ID!");
        } catch (IllegalArgumentException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }

        if (id1.length() != 6) {
            outputTA.setText("Register unsuccessfully, please key in customer ID in 6 digits!");
            idTF1.setText("");
        } else if ((name.length() == 0) || (home.length() == 0) || (email.length() == 0)) {
            outputTA.setText("Register unsuccessfully, please fill in all the information!");
        } else {
            customerList[customerCount] = new Customer(name, id1, home, email);
            customerCount++;
            try {
                File fl1 = new File("Customer Registration.txt");
                FileWriter fw1 = new FileWriter(fl1);
                PrintWriter pw1 = new PrintWriter(fw1);
                pw1.println(name);
                pw1.println(id1);
                pw1.println(home);
                pw1.println(email);
                pw1.close();
                fw1.close();
            } catch (FileNotFoundException ex) {
                JOptionPane.showMessageDialog(null, "Error! File not found!");
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, "Write operation fails!");
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "Illegal Customer ID!");
            } catch (IllegalArgumentException ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage());
            }
            outputTA.setText("1 new customer has been succesfully added!");
        }
    }

Save Order button

private void saveBTNActionPerformed(java.awt.event.ActionEvent evt) {                                        
        outputTA.setText("");
        String id = "", amountPaid = "", orderDate = "";
        int unitIndex = 0;
        try {
            id = idTF.getText();
            String home = homeTF.getText();
            String email = emailTF.getText();
            String name = nameTF.getText();
            unitIndex = restaurantNameCB.getSelectedIndex();
            orderDate = orderDateTF.getText();
            if (orderDate.equals("")) {
                throw new IllegalArgumentException("You must specify order date!");
            }
            amountPaid = amountPaidTF.getText();
            if (amountPaid.equals("")) {
                throw new IllegalArgumentException("You must specify amount paid!");
            }
            double amountP = Double.parseDouble(amountPaid);
            for (int i = 0; i < customerCount; i++) {
                if (id.equals(customerList[i].getID())) {
                    id = customerList[i].getID();
                    unitIndex = customerList[i].getRestaurantName();
                    orderDate.equals(customerList[i].getOrderDate());
                    amountP = customerList[i].getAmountPaid();
                    customerList[customerCount] = new Order(name, id, home, email, unitIndex, orderDate, amountP);
                }
            }
            outputTA.setText("Add order successfully!");
        } catch (IllegalArgumentException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
        if (id.length() != 6) {
            outputTA.setText("Register unsuccessfully, please key in customer ID in 6 digits!");
            idTF1.setText("");
        } else if ((orderDate.length() == 0) || (amountPaid.length() == 0)) {
            outputTA.setText("Register unsuccessfully, please fill in all the information!");
        } else {
            File fl = new File("Customer Order.txt");
            try {
                FileWriter fw = new FileWriter(fl);
                PrintWriter pw = new PrintWriter(fw);
                pw.println(id);
                pw.println(unitIndex);
                pw.println(orderDate);
                pw.println(amountPaid);
                pw.close();
                fw.close();
            } catch (FileNotFoundException ex) {
                JOptionPane.showMessageDialog(null, "Error! File not found!");
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, "Error! ");
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "Fill in the blanks!");
            } catch (IllegalArgumentException ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage());
            }
        }
    }
Gigi
  • 3
  • 3
  • 2
    Why does Order extend Customer? An order is not a type of customer. – NomadMaker Jun 28 '21 at 02:07
  • Because I am thinking to relate the Order with the Customer, what method can I use? – Gigi Jun 28 '21 at 03:09
  • Making order a subclass of customer doesnt relate an order to a single customer, especially if you may eventually have multiple orders for each customer. I would have a collection (List or Map) of orders that are associated with each custsomer. – NomadMaker Jun 28 '21 at 03:59
  • What if using the array of object? List is not permitted to use – Gigi Jun 28 '21 at 04:00
  • Arrays are fine, but you might have to deal with things that are already written into the ArrayList class. – NomadMaker Jun 28 '21 at 04:02
  • Can you show some example? – Gigi Jun 28 '21 at 04:07

1 Answers1

0

As NomadMaker mentioned, Order should NOT extend Customer, since it's not a type of a Customer.

If you have a restaurant, a type of customer can be a Person (someone who walks into the restaurant and orders food and eats it there) or a Company (a company could order food from your restaurant for its employees).

You're mixing database entities in a relational database with Objects in programming.

Anyway, this is how I'd do it.

DISCLAIMER: Haven't actually tested this!

Your Main Class + Save Button

public class MyMainClass {

    // Consider changing 'MAX' to 'CUSTOMER_MAX'
    final int CUSTOMER_MAX = 100;
    int customerCount = 0;
    Customer[] customerList = new Customer[CUSTOMER_MAX];

    final int ORDER_MAX = 100;
    int orderCount = 0;
    Order[] orderList = new Order[ORDER_MAX];

    final int CUSTOMER_ORDER_MAX = 100;
    int customerOrderCount = 0;
    CustomerOrder[] customerOrderList = new CustomerOrder[CUSTOMER_ORDER_MAX];

    // Needed for the 'random string' generation.
    Random randomNumber = new Random();
    String stringCharacters = "ABCDEFGHIJKLMNOP1234567890";
    int orderIDLength = 6;

    /**
     * Use this method to get a 'Customer' object using only the 'id'
     * (assuming 'id' is UNIQUE)
     * @param customerID
     * @param customerList
     * @param customerCount
     * @return 'Customer' Object - Will be 'null' if no 'Customer' is found.
     */
    public Customer getCustomerFromList(String customerID, Customer customerList[], int customerCount) {

        Customer customer = new Customer();

        for (int i = 0; i < customerCount; i++) {
            if (customerID.equals(customerList[i].getId())) {
                customer = customerList[i];
            }
        }

        return customer;
    }

    /* We'll need a way to generate a UNIQUE Order identification number.
       For your example, you can do so in 2 ways:

       1. Read the 'CustomerOrder.txt' file and count the amount of
       'Order's for whichever 'Customer' you need,
       then save that count number in a variable and add '+1' to it.
       After which, convert it to a 'String' and then use it when you're
       creating a new 'Order' Object.

       2. Generate a random string.
       https://stackoverflow.com/questions/2863852/how-to-generate-a-random-string-in-java

       The first option is more correct, but since you're saving the data
       in Arrays, I'll use the second option to save some code and time.

       Also, do NOT rely on the random string generation for database primary keys!
       In that case, either let the database use AUTOINCREMENT for the Primary Keys
       or use 'UUID'.
       
       A UNIQUE identification number is also needed for the
       CustomerOrder, so I'll re-use this method.
    */
    public String generateRandomStringID(Random rng, String characters, int length) {

        char[] text = new char[length];

        for (int i = 0; i < length; i++) {
            text[i] = characters.charAt(rng.nextInt(characters.length()));
        }

        return new String(text);
    }

    // Save Button
    private void saveBTNActionPerformed(java.awt.event.ActionEvent evt) {
        outputTA.setText("");
        String id = "", amountPaid = "", orderDate = "";

        // Do NOT initialize it with a '0', '0' is still a valid index
        // in a 'ComboBox' and can cause problems if not used carefully.
        int unitIndex;

        // Fictional 'restaurant' & 'amount'
        // SEE -> 'Order' Class
        int restaurant;
        String amount = "";

        id = idTF.getText();

        // Use the 'id' to find the 'Customer' object in the
        // 'customerList' array.
        Customer customer = getCustomerFromList(id, customerList, customerCount);

        try {

            // Fictional '.getSelectedIndex()' method
            // SEE -> 'Order' Class
            restaurant = restaurantCB.getSelectedIndex();

            unitIndex = restaurantNameCB.getSelectedIndex();
            orderDate = orderDateTF.getText();

            if (orderDate.equals("")) {
                throw new IllegalArgumentException("You must specify order date!");
            }

            amountPaid = amountPaidTF.getText();

            if (amountPaid.equals("")) {
                throw new IllegalArgumentException("You must specify amount paid!");
            }

            // Fictional '.getText()' method
            // SEE -> 'Order' Class
            amount = amountTF.getText();
            double amountDouble = Double.parseDouble(amount);

            double amountP = Double.parseDouble(amountPaid);

            // Create the 'Order' Object
            Order order = new Order(
                    generateRandomStringID(randomNumber, stringCharacters, orderIDLength),
                    orderDate,
                    unitIndex,
                    restaurant,
                    amountDouble,
                    amountP);

            // Check if 'order' exists
            boolean orderExists = false;

            for (int x = 0; x < orderCount; x++) {
                if (order.getOrder().equals(orderList[x])) {
                    orderExists = true;
                    // Throw Error
                }
            }

            // If the 'order' is NOT in the 'orderList'
            // Add it
            if (!orderExists ) {
                orderCount++;
                orderList[orderCount] = order;
            }

            if (customer.getId().length() != 6) {
                outputTA.setText("Register unsuccessfully, please key in customer ID in 6 digits!");
                idTF1.setText("");
            } else if ((orderDate.length() == 0) || (amountPaid.length() == 0)) {
                outputTA.setText("Register unsuccessfully, please fill in all the information!");
            } else {

                // Now we need to associate the 'order'
                // with the 'customer'. For that we create
                // a 'CustomerOrder' object.
                CustomerOrder customerOrder = new CustomerOrder(
                        generateRandomStringID(randomNumber, stringCharacters, orderIDLength),
                        customer,
                        order);

                // Check if 'customerOrder' exists
                boolean customerOrderExists = false;

                for (int x = 0; x < customerOrderCount; x++) {
                    if (customerOrder.getCustomerOrderID().equals(customerOrderList[x].getCustomerOrderID())) {
                        customerOrderExists = true;
                        // Throw Error
                    }
                }

                // If the 'customerOrder' is NOT in the 'customerOrderList'
                // Add it
                if (!customerOrderExists ) {
                    customerOrderCount++;
                    customerOrderList[customerOrderCount] = customerOrder;
                }

                // Write the 'customerOrder' to 'CustomerOrder.txt'
                customerOrder.writeCustomerOrder();

                outputTA.setText("Add order successfully!");
            }

        } catch (IllegalArgumentException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }
}

Customer

public class Customer {
    protected String name;
    protected String id;
    protected String home;
    protected String email;

    /* Consider having an empty constructor
       so you can instantiate the object without
       having to set variables.
    */
    public Customer(){}

    public Customer(String id, String name, String home, String email){
        this.id = id;
        this.name = name;
        this.home = home;
        this.email = email;
    }

    // Getters & Setters
}

Order

public class Order {

    // Reordered them for readability
    String order;
    String orderDate;
    /* You don't seem to be obtaining data for this from anywhere
       so I'm assuming either this or 'restaurantName' is not necessary
       and you added it by mistake in your Original Post,
       but I'll add a 'fictional' '.getSelectedIndex()' method in the
       'Save Button' method just in case.
    */
    int restaurant;
    int restaurantName;

    // Same as 'restaurant'.
    double amount;
    double amountPaid;

    /* Consider having an empty constructor
       so you can instantiate the object without
       having to set variables.
    */
    public Order(){}

    public Order(String order, String orderDate, int restaurant, int restaurantName, double amount, double amountPaid){

        this.order = order;
        this.orderDate = orderDate;
        this.restaurant = restaurant;
        this.restaurantName = restaurantName;
        this.amount = amount;
        this.amountPaid = amountPaid;
    }

    // Getters & Setters
}

CustomerOrder

public class CustomerOrder {

    String customerOrderID;
    Customer customer;
    Order order;

    public CustomerOrder(String customerOrderID, Customer customer, Order order) {
        this.customerOrderID = customerOrderID;
        this.customer = customer;
        this.order = order;
    }

    // Getters & Setters

    public void writeCustomerOrder() {

        File customerOrders = new File("CustomerOrders.txt");

        try {

            FileWriter fw = new FileWriter(customerOrders);
            PrintWriter pw = new PrintWriter(fw);

            pw.println("---------- CUSTOMER DATA ----------");

            pw.println("ID:" + this.getCustomer().getId());
            pw.println("Name: " + this.getCustomer().getName());
            pw.println("Home: " + this.getCustomer().getHome());
            pw.println("Email: " + this.getCustomer().getEmail());

            pw.println("---------- ORDER DATA ----------");
            pw.println("ID: " + this.getOrder().getOrder());
            pw.println("Order Date: " + this.getOrder().getOrderDate());
            pw.println("Restaurant ID: " + this.getOrder().getRestaurant());
            pw.println("Restaurant Name: " + this.getOrder().getRestaurantName());
            pw.println("Food Price: " + this.getOrder().getAmount());
            pw.println("Amount Paid: " + this.getOrder().getAmountPaid());

            pw.close();
            fw.close();
        } catch (FileNotFoundException ex) {
            JOptionPane.showMessageDialog(null, "Error! File not found!");
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "Error! ");
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "Fill in the blanks!");
        } catch (IllegalArgumentException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }

    }

}

P.S. Avoid naming variables a,b,c,d,e,f,etc. unless it's for something like a for loop.

P.P.S. Avoid using 'return' or 'break' ONLY to get out of loops unless absolutely necessary. I've been told it nurtures bad loop writing in the long run.

Doombringer
  • 596
  • 4
  • 19