在我的程序中,我必须能够从arrayList中删除项目。用户输入一个数字,然后如果它存在于arrayList中,则将其删除。当我按下删除按钮时,程序会崩溃,如果不是我的尝试和捕获语句,是否有人知道我应该更改以便删除才能正常工作?
public class SumElements extends javax.swing.JFrame {
ArrayList <Integer> values = new ArrayList();
...
private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {
try {
//declare variables
int searchVal = Integer.parseInt(valueInput.getText());
//search array for inputed value
int index = Collections.binarySearch(values, searchVal);
if (index >= 0){
//clear outputArea
outputArea.setText(null);
outputLabel.setText(null);
//remove from array
values.remove(valueInput.getText());
//display updated values
Collections.sort(values);
for (int i = 0; i < values.size(); i++)
{
outputArea.setText(outputArea.getText() + values.get(i) + "\n");
}
//clear input
valueInput.setText(null);
}
else {
outputLabel.setText("Data not found. Please try again.");
}
}
//set default
catch (NumberFormatException a)
{
outputLabel.setText("Please input a valid number.");
}
}