转换程序以使用ArrayLists的数组INSTEAD

时间:2018-01-16 04:07:49

标签: java arrays arraylist

我有一个类ShoppingCart,它使用ArrayList方法来执行程序,该程序基本上是一个程序,您可以在其中添加杂货到您的购物车等。但是,我想使用数组来代替ArrayLists来执行程序,因为我想处理我的数组知识。这是ShoppingCart类

import java.util.*;

@SuppressWarnings("serial")
public class ShoppingCart extends ArrayList<Selections> {

    // FIELDS
    private boolean discount;
    // Selections[]......

    // CONSTRUCTOR
    public ShoppingCart() {
        super();
        discount = false;
    }

    // Adding to the Collection
    public boolean add(Selections next) {
        // check to see if it's already here
        for (int i = 0; i < this.size(); i++)
            if (get(i).equals(next)) {
                set(i, next); // replace it
                return true;
            }
        super.add(next); // add new to the array
        return false;
    }

    // The GUI only know if check is on or off
    public void setDiscount(boolean disc) {
        discount = disc; // match discount from GUI
    }

    // total of selections
    public double getTotal() {
        double sum = 0.0;
        for (int i = 0; i < this.size(); i++)
            sum += get(i).priceFor();
        if (discount) sum *= 0.9;
        return sum;
    }
}

用于个别杂货的选择类。

import java.text.*;
// W.P. Iverson, instructor
// January 2018 for CS211
// Class that combines Item and ItemOrder

public class Selections {
    // FIELDS
    private String name;        // friendly name
    private double price;       // cost of one
    private int bulkQuantity;   // when bulk price kicks in
    private double bulkPrice;   // price for the bulk quantity
    private int quantity;       // how many we are buying

    private boolean hasBulk;    // internally used    
    private NumberFormat curr;  // for nice $12.34 currency formatting

    // CONSTRUCTORS
    public Selections(String name, double price) {
        this(name, price, -99999, 99999.); // flag that nothing is selected with 99999
    }

    public Selections(String thing, double amount, int qty, double bulk) {
        name = thing;
        price = amount;
        if (qty > 0) hasBulk = true;
        bulkQuantity = qty;
        bulkPrice = bulk;
        quantity = 0;  // starts with zero selected by user, GUI changes it later
        curr = NumberFormat.getCurrencyInstance();   
    }

    // decides how many we're buying
    public void setQuantity(int number) {
        quantity = number;
    }

    // calculates the price for this quantity
    public double priceFor() {
        if (hasBulk && quantity >= bulkQuantity)
            return quantity / bulkQuantity * bulkPrice + quantity % bulkQuantity * price;
        else
            return quantity * price;
    }

    // basic output for console or GUI text
    public String toString() {
        if (hasBulk)
            return name + ", " + curr.format(price) + " (" + bulkQuantity + " for " + curr.format(bulkPrice) + ")";
        else
            return name + ", " + curr.format(price);
    }
}

我已经为程序创建了一个JFrame,但只是想让它使用常规数组!谢谢你的帮助。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;

@SuppressWarnings("serial")
public class ShoppingFrame extends JFrame {
    private ShoppingCart items;
    private JTextField total;

    public ShoppingFrame(Selections[] array)      {
        // create frame and order list
        setTitle("CS211 Shopping List");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        items = new ShoppingCart();

        // set up text field with order total
        total = new JTextField("$0.00", 12);
        total.setEditable(false);
        total.setEnabled(false);
        total.setDisabledTextColor(Color.BLACK);
        JPanel p = new JPanel();
        p.setBackground(Color.blue);
        JLabel l = new JLabel("order total");
        l.setForeground(Color.YELLOW);
        p.add(l);
        p.add(total);
        add(p, BorderLayout.NORTH);

        p = new JPanel(new GridLayout(array.length, 1));
        for (int i = 0; i < array.length; i++)
            addItem(array[i], p);
        add(p, BorderLayout.CENTER);

        p = new JPanel();
       add(makeCheckBoxPanel(), BorderLayout.SOUTH);

        // adjust size to just fit
        pack();
    }

    // Sets up the "discount" checkbox for the frame
    private JPanel makeCheckBoxPanel() {
        JPanel p = new JPanel();
        p.setBackground(Color.blue);
        final JCheckBox cb = new JCheckBox("qualify for discount");
        p.add(cb);
        cb.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                items.setDiscount(cb.isSelected());
                updateTotal();
            }
        });
        return p;
    }

    // adds a product to the panel, including a textfield for user input of
    // the quantity
    private void addItem(final Selections product, JPanel p) {
        JPanel sub = new JPanel(new FlowLayout(FlowLayout.LEFT));
        sub.setBackground(new Color(0, 180, 0));
        final JTextField quantity = new JTextField(3);
        quantity.setHorizontalAlignment(SwingConstants.CENTER);
        quantity.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                updateItem(product, quantity);
                quantity.transferFocus();
            }
        });
        quantity.addFocusListener(new FocusAdapter() {
            public void focusLost(FocusEvent e) {
                updateItem(product, quantity);
            }
        });
        sub.add(quantity);
        JLabel l = new JLabel("" + product);
        l.setForeground(Color.white);
        sub.add(l);
        p.add(sub);
    }

    // When the user types a new value into one of the quantity fields,
    // parse the input and update the ShoppingCart.  Display an error
    // message if text is not a number or is negative.
    private void updateItem(Selections product, JTextField quantity) {
        int number;
        String text = quantity.getText().trim();
        try {
            number = Integer.parseInt(text);
        } catch (NumberFormatException error) {
            number = 0;
        }
        if (number <= 0 && text.length() > 0) {
            Toolkit.getDefaultToolkit().beep();
            quantity.setText("");
            number = 0;
        }
        product.setQuantity(number);
        items.add(product);
        updateTotal();
    }

    // reset the text field for order total
    private void updateTotal() {
        double amount = items.getTotal();
        total.setText(NumberFormat.getCurrencyInstance().format(amount));
    }

    public static void main(String[] args) {
        Selections[] array = new Selections[10];
        array[0] = new Selections("silly putty", 3.95, 10, 19.99);
        array[1] = new Selections("silly string", 3.50, 10, 14.95);
        array[2] = new Selections("bottle o bubbles", 0.99);
        array[3] = new Selections("Nintendo Wii system", 389.99);
        array[4] = new Selections("Mario Computer Science Party 2 (Wii)", 49.99);
        array[5] = new Selections("Don Knuth Code Jam Challenge (Wii)", 49.99);
        array[6] = new Selections("Computer Science pen", 3.40);
        array[7] = new Selections("Rubik's cube", 9.10);
        array[8] = new Selections("Computer Science Barbie", 19.99);
        array[9] = new Selections("'Java Rules!' button", 0.99, 10, 5.0);

        ShoppingFrame f = new ShoppingFrame(array);
        f.setVisible(true);
    }
}

1 个答案:

答案 0 :(得分:0)

您可以在ShoppingCart类中使用数组成员变量,如下所示:

private Selections[] selectionsArray;

而不是扩展ArrayList<Selections>。 (然后你必须自己处理调整阵列的大小。)