简体   繁体   English

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

[英]Why won't my displayAll() method print the values stored in the ArrayList? Why does it come out with Null's and 0's?

I've been working on creating a GUI to store details of gadgets such as Mobiles and MP3's.我一直致力于创建一个 GUI 来存储诸如手机和 MP3 之类的小工具的详细信息。 After storing some objects of these gadgets into the Array List and then hitting the displayAll() button, it does not display the values of them but rather Nulls and 0's.将这些小工具的一些对象存储到数组列表中,然后点击 displayAll() 按钮后,它不会显示它们的值,而是显示空值和 0。

I have tried everything to the point of giving up.我已经尝试了一切到放弃的地步。

Just below you will find the GUI class and then the Gadget Superclass and Mobile Subclass.您将在下方找到 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;
    }

Below are the methods to create, store and display the objects in to the ArrayList下面是在 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("");
    }
}

Below is the Mobile subclass下面是 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.");
    }
}

Below is the Gadget Superclass下面是小工具超类

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);
    }
}

I would very much appreciate all the help that I can get just to display the details correctly.我非常感谢我能得到的所有帮助,以正确显示细节。 Thanks.谢谢。

You have made one major mistake in your code.您在代码中犯了一个重大错误。 According to your code addMobile method must be根据您的代码 addMobile 方法必须是

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

The values for myCredit,theModel,theSize,theWeight,thePrice,theMemory are never assigned anywhere in your code. myCredit,theModel,theSize,theWeight,thePrice,theMemory的值永远不会在您的代码中的任何地方分配。 Various get methods have been written to get the values form the TextFields, but the methods have never been called.已经编写了各种 get 方法来从 TextField 获取值,但从未调用过这些方法。

The same goes for addMP3 method too. addMP3方法也是如此。 Make sure you call the constructor for Mobile and MP3 with proper values.确保使用正确的值调用 Mobile 和 MP3 的构造函数。 There is nothing wrong with the rest of your code.您的其余代码没有任何问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM