如果你想添加整数到一个数组:
你的代码设置从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();
}
,所以我不能从文本字段拆分一串数字,并说它们相加? – Aaron 2014-09-13 19:11:24
不,除非你使用一些正则表达式技术进行一种分割! – 2014-09-13 19:12:29
@Aaron:你也可以使用Scanner对象来解析输入。请参阅编辑以回答 – 2014-09-13 19:14:39