简体   繁体   中英

Adding user input to array

Got a program that takes user input from JTextFeld and adds them to a JTextArea. Here's the action listener class:

/**
 * Action listener class for reading in data and processing it
 * when the Add reading button is clicked.
 */
class AddReadingListener implements ActionListener
{
    public void actionPerformed(ActionEvent event)
    {
        // Fetch the new reading details

            int newDay = Integer.parseInt(dayEntryField.getText());
            double newRain = Double.parseDouble(rainEntryField.getText());

            // Clear the input
            dayEntryField.setText("");
            rainEntryField.setText("");
            dataArea.append(newDay + ": " + newRain + " cm" + "\n");
        }
    }
}

I've created an array to store the user input, however I don't know how to store the values from the JLabel into the array? I assume its something that needs to be implemented in the action listener class when the button is pressed?

public void getRain()
{
    double[] rArray = new double[32];
    for(int c = 0;c<rArray.length;c++)
    {
        rArray[1] = Integer.parseInt(""+dayEntryField);
    }
}

Doubt the array is correct, but any help would be appreciated!

Your question doesn't state if you want the two inputs to be linked in any way. If you do you should be using a HashMap (or you could use two ArrayLists if you find that easier).

The method you currently have is not working. I'll explain below:

public void getRain() //if you create a method that adds something, it should be named addRain() instead
{
    double[] rArray = new double[32]; //This creates a array with size 33
    for(int c = 0;c<rArray.length;c++) // here you create a loop that will run 33 times
    {
        rArray[1] = Integer.parseInt(""+dayEntryField); // This will input the value thats in the variable dayEntryField in index 1 of the array.
                                                        //This is not what you want since it will overwrite the current value thats in index 1 each time.
    }
} // End of method. Since you have added the value to an array that was created inside this method, the array will be removed by the garbage collector at this point. Hence your data will not be saved!

What you need to do:

//Create the list outside the method
private ArrayList<Double> arr = new ArrayList<Double>();

public void addRain() // You could also design the method to take an array as parameter, and add the data to that list (which is normally what you do(
{
   arr.add(dayEntryField); //altho, since adding element is a one-liner this could easily be done inside your listener. If you have your arraylist inside a class you will need a method tho.
}

This is about as much help I can give you without seeing any more code. But remember:

  1. Use ArrayList over array since it's dynamic and is easier to work with
  2. Make sure that the arraylist is initalized outside the method (if you use a method to add the value)
  3. Make sure that the name of your methods corresponds to what they are doing

You could try something like this:

   public class RainApplet extends JFrame {


   public RainApplet(){

   final JTextField rainEntryField = new JTextField("0", 10);

   final JTextField dayEntryField = new JTextField("0", 10);

   final JTextArea dataArea = new JTextArea("", 10, 10);

         rainEntryField.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e) {
                      // Fetch the new reading details

                    int newDay = Integer.parseInt(dayEntryField.getText());
                    double newRain = Double.parseDouble(rainEntryField.getText());

                    // Clear the input
                    dayEntryField.setText("");
                    rainEntryField.setText("");
                    dataArea.append(newDay + ": " + newRain + " cm" + "\n");

                    arr.add(newRain);
                                 }



    // end of ActionListener
        });

        // create new JPanel 'content' and add all components using BorderLayout
        JPanel content = new JPanel();
        content.setLayout(new BorderLayout(5, 5));

        // placing components around the JPanel
        content.add(rainEntryField , BorderLayout.NORTH);
        content.add(  dayEntryField, BorderLayout.EAST );
        content.add(  dataArea , BorderLayout.EAST );


        // set desirable properties for panel
        this.setContentPane(content);
        this.pack();
        this.setTitle("Rain Applet");
        this.setResizable(false);
        this.setLocationRelativeTo(null);
        this.setVisible(true);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);

           }

             private ArrayList<Double> arr = new ArrayList<Double>();

            public void addRain(Double d)  
            {
               arr.add(d); 
              }
               }

This should do the trick and uses the array above for reasons explained by @John Snow

使用ArrayList<Double>而不是double数组,并返回它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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