简体   繁体   中英

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

This is because you set the text of valueInput to null (with valueInput.setText(null) ) before calling Integer.parseInt(valueInput.getText()) which will throw a NumberFormatException of the following type:

Exception in thread "main" java.lang.NumberFormatException: null
    at java.lang.Integer.parseInt(Integer.java:542)
    at java.lang.Integer.parseInt(Integer.java:615)

So simply remove the line valueInput.setText(null);

You can parse only those strings, which represents numbers. The String variable which is pointing to null is definitely not representing the number. What I would suggest is to modify the code in this way:

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

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

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

在完成对输入的解析并将其保存为变量之后,请// //清除outputArea!

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