如果你想添加整數到一個數組:
你的代碼設置從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