mardi 4 octobre 2016

Adding Integers to an Array in Java

I have to create a program that accepts user input of numbers and then adds them to an ArrayList and then manipulates the data in several ways. The numbers must greater than or equal to 0. I am having an issue with adding the user input to the ArrayList, my try and catch statements stop the program from crashing but I can't add anything to the ArrayList, can someone tell me what I'm doing wrong in my adding process? Here's my code:

import java.util.ArrayList;
import java.util.Collections;

public class SumElements extends javax.swing.JFrame {
ArrayList <Integer> values = new ArrayList();

...

private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          
    try
    {

        //clear outputArea
        outputArea.setText(null);
        valueInput.setText(null);
        outputLabel.setText(null);

        //declare variables
        int value = Integer.parseInt(valueInput.getText());

        //validate input
        if (value >= 0){
            //add item to array
            values.add(value);

            //display values
            Collections.sort(values);
            for (int i = 0; i < values.size(); i++)
            {
                outputArea.setText(outputArea.getText() + values.get(i) + "\n");
            }
        }
    }
    //set default
    catch (NumberFormatException a)
    {
     outputLabel.setText("Please input a valid number.");
    }
}                   

Aucun commentaire:

Enregistrer un commentaire