【问题标题】:How to enter integers to a textfield and add them to an array? [closed]如何在文本字段中输入整数并将它们添加到数组中? [关闭]
【发布时间】:2014-09-13 19:03:09
【问题描述】:
public void actionPerformed(ActionEvent BUTTON_PRESS) { 

    if(BUTTON_PRESS.getSource() == button){                        

            /* Would like to use the TextField input as a Scanner here */

            outputField.setText(output);
        }
    }

我希望接受用户输入并使用“整数”来执行诸如 mean 、 avg 等计算。

这可能吗?

感谢您的帮助。

【问题讨论】:

    标签: java arrays swing java.util.scanner jtextfield


    【解决方案1】:

    如果您尝试将整数添加到数组中:

    您的代码从 JTextField 设置文本,这似乎与您希望做的相反。而是通过getText() 从 JTextField 中获取文本,通过Integer.parseInt(...) 将其转换为 int,然后将其放入您的数组中。

    类似:

    public void actionPerformed(ActionEvent evt) {
       String text = myTextField.getText();
       int myInt = Integer.parseInt(text); // better to surround with try/catch
       myArray[counter] = myInt;
       counter++; // to move to the next counter
    }
    

    如果您尝试进行数值计算,则不需要数组,您的问题会非常混乱。


    编辑
    关于您的评论:

    所以我不能从文本字段中拆分一串数字并说将它们加在一起?

    您可以使用 Scanner 对象来解析它:

    public void actionPerformed(ActionEvent evt) {
       String text = myTextField.getText();
       Scanner scanner = new Scanner(text);
       // to add:
       int sum = 0;
       while (scanner.hasNextInt()) {
          sum += scanner.nextInt();
       }
       scanner.close();
       outputField.setText("Sum: " + sum);
    }
    

    或者...

    public void actionPerformed(ActionEvent evt) {
       List<Integer> list = new ArrayList<Integer>();
       String text = myTextField.getText();
       Scanner scanner = new Scanner(text);
       // to add to a list
       while (scanner.hasNextInt()) {
          list.add(scanner.nextInt());
       }
       scanner.close();
    
       // now you can iterate through the list to do all sorts of math operations
       // outputField.setText();
    }
    

    【讨论】:

    • 所以我不能从文本字段中拆分一串数字并说将它们加在一起?
    • 不,除非您使用一些正则表达式技术执行某种拆分!
    • @Aaron:您还可以使用 Scanner 对象来解析输入。请参阅编辑以回答
    • 谢谢@HovercraftFullOfEels 你太客气了
    猜你喜欢
    • 2020-07-09
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 2015-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多