2014-09-13 53 views
-1
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); 
     } 
    } 

我希望在用户输入,并使用“整数”进行计算,如平均值,AVG等如何将整数输入到文本字段并将它们添加到数组中?

这可能吗?

感谢您的任何帮助。

回答

2

如果你想添加整数到一个数组:

你的代码设置从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 
} 

如果你试图做数值计算,那么就没有必要为一个数组,你的问题会非常混乱。


编辑
关于你的评论:

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

你可以使用扫描仪对象来分析它:

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(); 
} 
+0

,所以我不能从文本字段拆分一串数字,并说它们相加? – Aaron 2014-09-13 19:11:24

+1

不,除非你使用一些正则表达式技术进行一种分割! – 2014-09-13 19:12:29

+0

@Aaron:你也可以使用Scanner对象来解析输入。请参阅编辑以回答 – 2014-09-13 19:14:39

相关问题