Java small shopping system (shopping cart)

front page

import java.util.Arrays;
import java.util.Scanner;

/*
Home page of product construction and purchase logic module
      Developer:XXXX
      Version:v1.1
 */
public class MyPage {
    public static void main(String[] args) {
        //In the entire program, mypay1 is instantiated, mypay1, mypay2, mypay3, mypay4, and mypay5 all need to be instantiated, assigned, and finally called.
        //mypay1, mypay2, mypay3, mypay4, mypay5 are globally valid in the entire main function
        //In the entire program, as long as it is related to numerical values, first, enter the numerical value to select, second, the variable names are similar, with one more numerical value
        //Array initialization, only 5 elements, only 5 products
        MyPay[] mypays=new MyPay[5];
        //Since MyPay inputs different parameters during initialization, make the parameters into an array.
        String[] names= {"Pojun",
                "breaking Dawn",
                "Wrath of the Loremaster",
                "Blade of Weeping Blood",
                "The Wrath of the Blood Demon"
        };
        //price array
        Double[] prices= {2976.0,3200.0,2120.6,1700.9,2210.8};
        //delivery array
        String[] peisongs= {"Shenzhen City to Jinzhong City, Shanxi",
                "Shanghai City to Jinzhong City, Shanxi Province",
                "Tianjin City to Jinzhong City, Shanxi Province",
                "Beijing City to Jinzhong City, Shanxi Province",
                "Jinan City to Jinzhong City, Shanxi Province"
        };
        //instantiate shopping cart
        MyCart mycart=new MyCart();
        //Display menu of product list
        System.out.println("---------------------------------");
        System.out.println("Welcome to my store");
        System.out.println("Version: v1.2");
        System.out.println("Modification content: optimized code after classification");
        System.out.println("---------------------------------");

        //Define the array and put these objects in the array. Each object in the array is equivalent to a commodity object. Here is the object of MyPay

        //The numbers are all 1, no array processing is done
        //Instantiate all products and traverse the array
        //The first layer traverses five MyPay objects, then traverses names, traverses prices, and traverses peisons. However, names, prices, and peisons are all one-level relationships.
        //The first level of loop is five objects. Each object is assigned a value. Just take out the elements in each array and assign them.
        for(int i=0;i<5;i + + ){
            mypays[i]=new MyPay();
            mypays[i].setName(names[i]);
            mypays[i].setPrice(prices[i]);
            mypays[i].setPeison(peisongs[i]);
            mypays[i].setNum(1);
            print_goods(i + 1,mypays[i].getName(),mypays[i].getPrice());
        }

        System.out.println("************************");
        //The above code allows the user to view the home page. After viewing the home page and entering the order page, there must be a user name.
        Scanner scanner = new Scanner(System.in);
        //Must hit enter, or the user won’t accept any characters they type. Users who are not logged in will not be accepted here.
        scanner.nextLine();
        //The user needs to log in to select products and remember the details. If init has been executed before, new Pay has been executed. The user name is not allowed to be entered in the previous content.
        System.out.println("Please log in as user");
        //Execute the 0 element in the mypays array for user login
        mypays[0].myinput();
        //All username and money from the 2nd to 5th elements in the mypays array are equal to the first element, and the assignment starts from the second element, where j=1
        for(int j=1;j<5;j + + ){
            mypays[j].setUsername(mypays[0].getUsername());
            mypays[j].setMoney(mypays[0].getMoney());
        }
        //The loop status can be controlled here. Through the status of the order, if the order is closed, there is no need to perform a while loop.
        //Because each product is instantiated once, it has an order status, which is determined according to the product selected by the user. There is no no outside the while.
        //Or only write once, you can use do---while, do---while to ensure that the loop body appears once
        //If you add to the shopping cart, keep adding to the shopping cart. The exit condition of the while loop is the purchase status of the last item.
        int no=1;
        do{
            //Only the product number is received here. If you use nextInt, an error will be reported. Use try -----catch directly.
            System.out.println("Please enter the product number you purchased:");
            try{
                no=scanner.nextInt();
                //After selecting the corresponding product, enter the product module. The product details are displayed in the product module, and there are two buttons to buy now and add to the shopping cart.
                //Call the display in the product module.
                //The display method of product 1 is called on the homepage. Here I want to reference the array subscript using i-1.
                mypays[no-1].show(mycart);
            }catch(Exception e){
                System.out.println("Thank you for using, you entered an error, please enter the number corresponding to the product");
            }
        } while(mypays[no-1].isStatus());
        //Finally hand it over to the main class to print other products in the shopping cart mycart, use enhanced for
        for(MyPay mygood:mycart.getCart()){
            if(mygood!=null){
                System.out.println(mygood.getName());
                System.out.println(mygood.getPeison());
                System.out.println(mygood.getPrice());
                System.out.println(mygood.getNum());
            }
        }

        //The logic is executed here, first output the shopping cart
// System.out.println(Arrays.toString(mycart.getCart()));


    }
    //Use functions to solve the problem of repeated code and inconsistent parameters in the code. Use multiple arrays in the loop to solve the problem. Here, we use function parameter passing.
    //To change the printing style later, you only need to change the function
    public static void print_goods(int i,String name,double price){
        System.out.println( i + "-" + name + "\t" + price);
    }

}

Product page

import java.util.Scanner;

/*
Modify the Goods class to become a standard for Java development
 */
public class MyGoods {
    //First, to meet the encapsulation characteristics, all variables are private
    private String name;
    private String character;
    private int num;
    private double price;
    // private String big_pic;
    private String small_pic;
    //Automatically generate a parameterless constructor
    public MyGoods() {
    }

    //Automatically generate a fully parameterized constructor. The main class main function calls this class and directly passes in the parameters. There is no need to generate an init method in the main class main.
    public MyGoods(String name, double price,String peison, int num) {
        this.name = name;
        this.peison = peison;
        this.num = num;
        this.price = price;
    }
    //The current product displayed in the current class, there is no way to display all products
    //Methods in normal logic
    //The method show to display all the products, the logic of the shopping cart may occur, the main class takes the shopping cart from the same unit
    public void show(MyCart mycart){


        //Display products first
        System.out.println(this.name);
        System.out.println(this.num);
        System.out.println(this.price);
        System.out.println(this.peison);
        //User adjusts quantity
        System.out.println("Please enter the quantity of goods purchased");
        Scanner scanner=new Scanner(System.in);
        //The quantity of goods here, if there is an error, continue to enter
        while(true){
            try{
                //The input quantity is directly given to this.num, the current object indicated by this
                this.num=scanner.nextInt();
                //Exit the loop after success
                break;
            }catch(Exception e){
                System.out.println("You need to re-enter the product quantity. There is something wrong with your input. Please enter an integer");
            }
        }
        System.out.println("**********************");
        System.out.println("1------Buy Now");
        System.out.println("2-------Add to cart");
        System.out.println("**********************");
        System.out.println("Please select your purchase intention and enter the serial number");
        try{
            //scanner is the global variable of this function in this class and can be used here
            int no=scanner.nextInt();
            switch(no){
                case 1:
                    this.buy();
                    break;
                case 2:
                    //The same shopping cart must be specified when calling. This shopping cart is instantiated in the main class, and the shopping cart is passed into this class.
                    this.addcar(mycart);
                    break;
            }
        }catch(Exception e) {
            //If the user makes a mistake, the buy now method will be selected by default.
            this.buy();
        }

    }
    //How to buy now
    public void buy(){

        System.out.println("You purchased this product");
        //The make_order() method of the Order order class is called here, an empty method is generated here, and rewritten in the Order class
        this.make_order(0.0);
    }

    //The class only represents the current product. In addcar, you can only add the current product to the shopping cart. No purchase or order task is performed.
    //The function of addcar here is to put the product in the shopping cart, but it is only the category of the current product, and cannot put different products in the same shopping cart.
    //The order starts after entering the shopping cart for settlement.
    //Method to add to shopping cart
    public void addcar(MyCart mycart){
        //Add the product to the shopping cart class to ensure that the product is added to a shopping cart. The shopping cart instance object cannot be instantiated here, and the instantiation here is not a shopping cart.
        //Make sure there is one shopping cart and the instance is in the main class
        //If there are shopping cart parameters, you can directly add to the shopping cart. This represents the current product. Directly call the addCart shopping cart method in the MyCart shopping cart class for the current product.
        mycart.addCart(this);
        System.out.println("You have added the product to the shopping cart");

    }
    //protected modification requires rewriting after class inheritance
    protected void make_order(double total){
        //The code is done by the order class, not by the Goods module, it can only be implemented by the developers of Order
    }

    //For ease of reading, these getter or setter methods are placed at the end of the code
    //Second, after encapsulating private variables, use the get method for variables that need to be valued, and use the set method for variables that need to be assigned. That is, both methods need to be obtained and assigned, that is, both methods are available.
    //For example, for name and get, add the first letter of the attribute in capital letters. The purpose of the get method is to require the user to obtain this value. Here is the return value
    public String getName(){
        return this.name;
    }
    //The set method only plays the role of an assignment and does not need to return a value. Because assignment is required, there must be parameters. The parameter name is a local variable.
    //Generally, the set method local variable has the same name as the attribute name in the class.
    public void setName(String name) {
        this.name=name;
    }

    public String getPeison() {
        return peison;
    }

    public void setPeison(String peison) {
        this.peison = peison;
    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getSmall_pic() {
        return small_pic;
    }

    public void setSmall_pic(String small_pic) {
        this.small_pic = small_pic;
    }
    //toString is placed at the end of the code

    @Override
    public String toString() {
        return "MyGoods{" +
                "name='" + name + ''' +
                ", peison='" + peison + ''' +
                ", num=" + num +
                ", price=" + price +
                ", small_pic='" + small_pic + ''' +
                '}';
    }
}

Order page

/*
Order class modified by java specification
 */
public class MyOrder extends MyGoods{

    //Only the private member variable total
    private double total=0;
    //You also need the status of the order being closed. This refers to adding to the shopping cart or purchasing directly. The status here is only closed or not closed. The default order is open.
    private boolean status=true;
    public MyOrder() {
        super();
    }

    //Generate a no-parameter construct to facilitate instantiation. Because the parent class has no parameters, the default here is a no-parameter construct.
    //Normal logic method
    //To rewrite, you need to add @Override to the method to indicate this method. The parent class also has it, and the subclass can rewrite it.
    //Overload the make_order method. This make_order does not need to calculate num()*price, just take out the total directly.
    //Is it possible to write make_order together without overloading?
    //The total here is the parameter passed from the shopping cart
    @Override
    protected final void make_order(double total){
        //The make_order method generates an order and the current order is closed
        this.status=false;
        //Generate an order number, which specifies an 8-digit integer
        long order_id=(int)(Math.random()*10000000 + 10000000);
        // When calculating double, please note that multiplication is not allowed. After changing to privatization, you cannot directly .num, .private. Here you need to use the get method to obtain the value.
        //this.num below. Call this.getNum, change this.price to this.getPrice
        //The initial value of total for buy now is 0, and the initial value for non-buy now is the sum value. The sum value comes from the result of the shopping cart, and the shopping cart result needs to be returned.
        if(this.total==0.0){
            this.total=this.getNum()*this.getPrice();
        }else{
            this.total=total;
        }

        //Format, keep decimal places
        this.total=Double.parseDouble(String.format("%.2f",this.total));
        //Leave the order page, go to the payment interface, call payment, instantiate,
        //The pay_order() method here is overridden by the Pay payment class. , the shopping cart carts are passed in here. This parameter comes from the shopping cart.
        this.pay_order();
    }

    //This method needs to be rewritten by the Pay class and does not require access. Change it to protected.
    protected void pay_order(){
        //This method is not implemented
    }
    //Do you need to generate a parameterized constructor? There is only one total constructor with parameters. The total here is calculated and not changed by user assignment. There is no need to do a parameterized constructor.
    //The total must be automatically calculated by this Order class, without the participation of external users. Change this value. The total here only has a getter method.
    public double getTotal() {
        return total;
    }
    //The added order status requires getter and setter methods

    public boolean isStatus() {
        return status;
    }

    public void setStatus(boolean status) {
        this.status = status;
    }
}

Shopping cart page

import java.util.Scanner;

/*
Put the addresses of different products in the shopping cart at the same address
The shopping cart is equivalent to instantiating new once
The product can new instantiate 5 different products
In this way, 5 different addresses are placed in the shopping cart of one address.
The class that generates the shopping cart
Attributes
 */
public class MyCart {
    //Private attribute. The attribute is an array. The array must be initialized. There are only 5 values here. If there is no current value, it is null.
    private MyPay[] carts=new MyPay[5];
    //Do the getter and setter methods. According to the logic, you can add the shopping cart and add the value to the cart. This is the setter method. The getter method takes out the shopping cart data.

    public MyPay[] getCart() {
        return carts;
    }
    //Function to generate orders
    public void createOrder(){
        System.out.println("Do you want to generate an order now? (y/n)");
        Scanner scanner=new Scanner(System.in);
        //User inputs y or n
        String answer=scanner.next();
        //The content entered by the user is y or n. All letters are case-sensitive.
        if(answer.toLowerCase().equals("y")){
            //Process order settlement, traverse the data, if it is not empty, there must be a price, and give the total price to the Order
            //This traversal does not require an index, you can use enhanced for
            //Find the sum of prices, find the sum of 1-100, and the sum value is defined outside the loop
            double sum=0;
            //Record the index of the product
            int index=0;
            for(MyPay mygood:carts){
                if(mygood!=null){
                    sum + =mygood.getNum()*mygood.getPrice();
                    index + + ;
                }
            }
            //Call the make_order method of the order class,
            //Every product added to the shopping cart can be purchased, and its status is true. Determine which product order status the main class uses to exit the loop.
            //According to logic, the purchase order status exiting the main loop is the last product. Here, call the make_order method to use the last product.
            //Although it is the last one in the array, the user may add 2 products and then settle the order. It is directly judged that there is a problem with 4, and the index of the product that is not empty is judged.
            //Need to print the product lastly, and the shopping cart of carts is required
            carts[index].make_order(sum);
        }else{

        }
    }
    //This set method is special. If you want to add it to the shopping cart, you don’t need to pass in all the contents of the shopping cart. The meaning of the MyGoods[] variable is all the contents of the shopping cart. You only need to pass in one product.
    //MyGoods is passed in here because of the this instruction added to the MyGoods class. This can only refer to the MyGoods type.
    public void addCart(MyGoods cart) {
        //The logic here adds the incoming products to the shopping cart, because the array only has 5 elements, and there is no value after initialization, which is null.
        //The object class array uses increased for traversal, for (single data type in the array variable name: array name)
        for(int i=0;i<5;i + + ){
            if (carts[i]==null){
                //If the current object is empty, it proves that there is no product in the shopping cart array. If there is no product, you can use index assignment.
                //Here you need to convert the incoming MyGoods to MyPay
                carts[i]=(MyPay)cart;
                //It is found that the product of a data is empty. After adding it, it will exit the loop directly. The subsequent products do not need to be judged as empty.
                break;
            }
        }
        //When adding to the shopping cart is completed, it needs to be judged whether to proceed with settlement of order closing.
        this.createOrder();
    }
}

Payment page

import java.util.Scanner;

/*
Pay class modified based on Java development specifications
 */
public class MyPay extends MyOrder{
    //Private all properties
    private String username;
    private double money;

    //No parameters, can automatically generate a parameterless one
    public MyPay() {
        //Directly generating the constructor of the parent class here will generate an error. I hope the constructor of the parent class is valid in the subclass, use super
        //Direct super(), call the constructor of the parent class
        super();
    }
    //There are parameters because values can be assigned to username and money
    public MyPay(String username, double money) {
        this.username = username;
        this.money = money;
    }

    //Normal logical code area
    //The user enters the username and password. The reason is not placed in the constructor. The user only needs to enter it once.
    public void myinput(){
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter the payment account name");
        this.username=scanner.next();
        System.out.println("Please enter the payment account balance:");
        try{
            this.money=scanner.nextDouble();
        }catch(Exception e){
            this.money=100;
        }
    }
    //Implement rewriting the pay_order method in Order
    //pay_order needs to get the items in the shopping cart
    @Override
    public void pay_order(){
        //Implement the payment logic and determine whether the current balance is larger or smaller than the order
        if(this.money>this.getTotal()){
            this.money=this.money-this.getTotal();
            System.out.println("Congratulations, you successfully purchased the product");
            System.out.println(this.getName());
            System.out.println(this.getPeison());
            System.out.println(this.getPrice());
            System.out.println(this.getNum());
            System.out.println(this.getTotal());
        }else{
            System.out.println("Brother, the money is not enough");
        }
    }
    //Simplify the process, the account and balance can be set, username and money have getter and setter methods
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }
}