【问题标题】:Adding Integers to an Array in Java在 Java 中将整数添加到数组中
【发布时间】:2016-10-04 19:18:17
【问题描述】:

我必须创建一个程序来接受用户输入的数字,然后将它们添加到 ArrayList 中,然后以多种方式处理数据。数字必须大于或等于 0。我在将用户输入添加到 ArrayList 时遇到问题,我的 try 和 catch 语句阻止程序崩溃,但我无法向 ArrayList 添加任何内容,有人可以告诉我什么我在添加过程中做错了吗? 这是我的代码:

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

【问题讨论】:

  • 您首先将valueInput 的文本设置为null,然后阅读它——您期望得到什么结果?

标签: java arrays if-statement for-loop arraylist


【解决方案1】:

这是因为您在调用Integer.parseInt(valueInput.getText()) 之前将valueInput 的文本设置为null(带有valueInput.setText(null)),这将引发以下类型的NumberFormatException

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

所以只需删除valueInput.setText(null);这一行

【讨论】:

    【解决方案2】:

    您只能解析那些代表数字的字符串。指向 null 的 String 变量绝对不代表数字。我建议以这种方式修改代码:

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

    【讨论】:

      【解决方案3】:

      在解析完输入并将它们保存到变量后,请执行 //clear outputArea!

      【讨论】:

        猜你喜欢
        • 2013-07-17
        • 2016-07-15
        • 1970-01-01
        • 1970-01-01
        • 2012-11-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多