为什么我的displayAll()方法不打印存储在ArrayList中的值?为什么会出现Null和0?

时间:2019-04-18 20:10:00

标签: java arraylist

我一直在创建GUI,以存储小工具(例如手机和MP3)的详细信息。将这些小工具的一些对象存储到“数组列表”中,然后单击displayAll()按钮后,它不会显示它们的值,而是显示Nulls和0。

我已经尽一切努力放弃了。

在下面,您将找到GUI类,然后是小工具超类和移动子类。

import java.util.ArrayList;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class GadgetShop implements ActionListener
{
    // instance variables - replace the example below with your own
    private JTextField modelTextField;
    private JTextField priceTextField;
    private JTextField weightTextField;
    private JTextField sizeTextField;
    private JTextField initialCreditTextField;
    private JTextField initialMemoryTextField;
    private JTextField phoneNumberTextField;
    private JTextField durationTextField;
    private JTextField downloadSizeTextField;
    private JTextField displayNumberTextField;
    private JButton addMobileButton;
    private JButton addMp3Button;
    private JButton clearButton;
    private JButton displayAllButton;
    private JButton makeCallButton;
    private JButton downloadMusicButton;
    private JLabel modelLabel;
    private JLabel priceLabel;
    private JLabel weightLabel;
    private JLabel sizeLabel;
    private JLabel creditLabel;
    private JLabel memoryLabel;
    private JLabel phoneNumLabel;
    private JLabel durationLabel;
    private JLabel downloadLabel;
    private JLabel dispNumLabel;
    private JFrame frame;
    private ArrayList<Gadget> gadgets;
    private int myCredit;
    private String theModel;
    private String theSize;
    private int theWeight;
    private double thePrice;
    private int theMemory;

    /**
     * The GUI is created in the constructor.
     */
    public GadgetShop()
    {
        // initialise instance variables

        gadgets = new ArrayList<Gadget>();

        frame = new JFrame("The Gadget Shop");
        Container contentPane = frame.getContentPane();
        contentPane.setLayout(new GridLayout(7, 4));

        JLabel modelLabel = new JLabel("Model:");
        contentPane.add(modelLabel);

        JLabel priceLabel = new JLabel("Price:");
        contentPane.add(priceLabel);

        JLabel weightLabel = new JLabel("Weight:");
        contentPane.add(weightLabel);

        JLabel sizeLabel = new JLabel("Size:");
        contentPane.add(sizeLabel);

        modelTextField = new JTextField(15);
        contentPane.add(modelTextField);

        priceTextField = new JTextField(15);
        contentPane.add(priceTextField);

        weightTextField = new JTextField(15);
        contentPane.add(weightTextField);

        sizeTextField = new JTextField(15);
        contentPane.add(sizeTextField);

        JLabel creditLabel = new JLabel("Credit:");
        contentPane.add(creditLabel);

        JLabel memoryLabel = new JLabel("Memory:");
        contentPane.add(memoryLabel);

        addMobileButton = new JButton("Add Mobile");
        contentPane.add(addMobileButton);
        addMobileButton.addActionListener(this);

        addMp3Button = new JButton("Add MP3");
        contentPane.add(addMp3Button);
        addMp3Button.addActionListener(this);

        initialCreditTextField = new JTextField(15);
        contentPane.add(initialCreditTextField);

        initialMemoryTextField = new JTextField(15);
        contentPane.add(initialMemoryTextField);

        clearButton = new JButton("Clear");
        contentPane.add(clearButton);
        clearButton.addActionListener(this);

        displayAllButton = new JButton("Display All");
        contentPane.add(displayAllButton);
        displayAllButton.addActionListener(this);

        JLabel phoneNumLabel = new JLabel("Phone No:");
        contentPane.add(phoneNumLabel);

        JLabel durationLabel = new JLabel("Duration:");
        contentPane.add(durationLabel);

        JLabel downloadLabel = new JLabel("Download:");
        contentPane.add(downloadLabel);

        JLabel dispNumLabel = new JLabel("Display Number:");
        contentPane.add(dispNumLabel);

        phoneNumberTextField = new JTextField(15);
        contentPane.add(phoneNumberTextField);

        durationTextField = new JTextField(15);
        contentPane.add(durationTextField);

        downloadSizeTextField = new JTextField(15);
        contentPane.add(downloadSizeTextField);

        displayNumberTextField = new JTextField(15);
        contentPane.add(displayNumberTextField);

        makeCallButton = new JButton("Make A Call");
        contentPane.add(makeCallButton);
        makeCallButton.addActionListener(this);

        downloadMusicButton = new JButton("Download Music");
        contentPane.add(downloadMusicButton);
        downloadMusicButton.addActionListener(this);

        frame.pack();
        frame.setVisible(true);
    }

    /**
     * The main method allows the program to be run without BlueJ.
     */ 
    public static void main(String[] args)
    {
        GadgetShop calculator = new GadgetShop();
    }

    /**
     * Find which button triggered the event and call the appropriate method.
     */
    public void actionPerformed(ActionEvent event)
    {
        String command = event.getActionCommand();
        if (command.equals("Add Mobile")) {
            addMobile();
        }
        if (command.equals("Add MP3")) {
            addMp3();
        }
        if (command.equals("Display All")) {
            displayAll();
        }
        if (command.equals("Make A Call")) {
            makeCall();
        }
        if (command.equals("Download Music")) {
            downloadMusic();
        }
        if (command.equals("Clear")) {
            clear();
        }
    }

    public String getModel()
    {
        String model
           = modelTextField.getText();
        return model;
    }

    public String getSize()
    {
        String size
           = sizeTextField.getText();
        return size;
    }

    public String getNumber()
    {
        String phoneNumber
           = phoneNumberTextField.getText();
        return phoneNumber;
    }

    public int getWeight()
    {
        int weight
           = Integer.parseInt(weightTextField.getText());
        return weight;
    }

    public double getPrice()
    {
        double price
           = Double.parseDouble(priceTextField.getText());
        return price;
    }

    public int getCredit()
    {
        int credit
           = Integer.parseInt(initialCreditTextField.getText());
        return credit;
    }

    public int getMemory()
    {
        int memory
           = Integer.parseInt(initialMemoryTextField.getText());
        return memory;
    }

    public int getDuration()
    {
        int duration
           = Integer.parseInt(durationTextField.getText());
        return duration;
    }

    public int getDownloadSize()
    {
        int downloadSize
           = Integer.parseInt(downloadSizeTextField.getText());
        return downloadSize;
    }

    public int numberOfGadgets()
    {
        return gadgets.size();
    }

    public int getDisplayNumber()
    {
        int displayNumber = -1;

        try {
            displayNumber
              = Integer.parseInt(displayNumberTextField.getText());
            if(displayNumber < 0) {
                JOptionPane.showMessageDialog(frame, 
                   "Please enter a positive number");
            }
            else if(displayNumber > numberOfGadgets()) {
                JOptionPane.showMessageDialog(frame, 
                   "Please enter a number in the correct range");
            }
        }
        catch(NumberFormatException exception) {
        }
        return displayNumber;
    }

下面是创建,存储和显示ArrayList对象的方法

    public void addMobile()
    {
        Mobile mobile = new Mobile(myCredit, theModel, theSize, theWeight, thePrice);
        gadgets.add(mobile);
    }

    public void addMp3()
    {
        Gadget mp3 = new MP3(theMemory, theModel, theSize, theWeight, thePrice);
        gadgets.add(mp3);
    }

    public void displayAll()
    {
        for(Gadget gadget : gadgets) {
            gadget.print();
            System.out.println();   // empty line between items
        }
    }

    public void makeCall()
    {
        //Nothing here atm
    }

    public void downloadMusic()
    {
        //Nothing here atm
    }

    public void clear()
    {
        modelTextField.setText("");
        sizeTextField.setText("");
        phoneNumberTextField.setText("");
        weightTextField.setText("");
        priceTextField.setText("");
        initialCreditTextField.setText("");
        initialMemoryTextField.setText("");
        durationTextField.setText("");
        downloadSizeTextField.setText("");
        displayNumberTextField.setText("");
    }
}

下面是Mobile子类

public class Mobile extends Gadget
{
    // instance variables - replace the example below with your own
    private int credit;

    /**
     * Constructor for objects of class Mobile
     */
    public Mobile(int myCredit, String theModel, String theSize, int theWeight, double thePrice)
    {
        // initialise instance variables
        super(theModel, theSize, theWeight, thePrice);
        credit = myCredit;
    }

    /**
     * This is an accessor method that allows the user to view the balance of credit remaining in the mobile phone.
     */
    public int getCredit()
    {
        return credit;
    }

    /**
     * This is a mutator method that allows the user to top up the credit on their mobile phone.
     */
    public void addCredit(int topUp)
    {
        if (topUp > 0) {
            credit = credit + topUp;
        }
        else {
            System.out.println("Please enter an amount greater than 0.");
        }
    }

    /**
     * This is a mutator method that allows the user to enter the phone number that they'd like to call and the duration of that call in minutes.
     */
    public void makeCall(String number, int minutes)
    {
        if (credit >= minutes) {
            System.out.println("You called this number: " + number + " for the duration of: " + minutes + " minute/s.");
            credit = credit - minutes;
            System.out.println(" ");
            System.out.println("You now have " + credit + " minutes of calling credit remaining in your balance.");
        }
        else {
            System.out.println("Sorry, but you have an insufficient amount of credit to make this call.");
        }
    }

    /**
     * This output method displays certain specifications of the mobile device such as the: Model, size, weight and price. The amount of credit remaining in the mobile is also displayed.
     */
    public void print()
    {
        super.print();
        System.out.println("You have " + credit + " minutes of credit remaining.");
    }
}

以下是小工具超类

public class Gadget
{
    // instance variables
    private String model;
    private String size;
    private int weight;
    private double price;


    /**
     * Constructor for objects of class Gadget
     */
    public Gadget(String theModel, String theSize, int theWeight, double thePrice)
    {
        // initialised instance variables
        model = theModel;
        size = theSize;
        weight = theWeight;
        price = thePrice;
    }

    /**
     * This is an accessor method that returns the model number of the gadget.
     */
    public String getModel()
    {
        return model;
    }

    /**
     * This is an accessor method that returns the size of the gadget.
     */
    public String getSize()
    {
        return size;
    }

    /**
     * This is an accessor method that returns the weight of the gadget.
     */
    public int getWeight()
    {
        return weight;
    }

    /**
     * This is an accessor method that returns the price of the gadget.
     */
    public double getPrice()
    {
        return price;
    }

    /**
     * This is an output method that displays the model, size, weight and price of an object to the user.
     */
    public void print()
    {
        System.out.println("Model: " + model);
        System.out.println("Size: " + size);
        System.out.println("Weight: " + weight);
        System.out.println("Price: " + price);
    }
}

非常感谢我能正确显示详细信息而获得的所有帮助。谢谢。

1 个答案:

答案 0 :(得分:0)

您在代码中犯了一个主要错误。根据您的代码,addMobile方法必须为

public void addMobile()
{
    Mobile mobile = new Mobile(getCredit(), getModel(), getSize(), getWeight(), getPrice());
    gadgets.add(mobile);
}

myCredit,theModel,theSize,theWeight,thePrice,theMemory的值从未在代码中的任何位置分配。已经编写了各种get方法来获取TextField的值,但从未调用过这些方法。

addMP3方法也是如此。确保使用正确的值调用Mobile和MP3的构造函数。其余代码没有任何问题。