Summing elements of an array list right after adding a new element in net beans causes the first element added to not be counted in the sum.Then when i add another element it only sums the second element added.Code is below and there is an image of my problem.
https://gyazo.com/12f13ab5724af3de8d9848994987910d
private void balanceAddActionPerformed(java.awt.event.ActionEvent evt) {
try {
outputBox.setText("");
String check = addInput.getText();
int check1 = check.length();
if ("".equals(check)) {
errorLabel.setText("Nothing has been entered to be added.");
for (int i = 0; i < balance.size(); i++) {
outputBox.setText(outputBox.getText() + balance.get(i) + "\n");
}
} else if (check1 >= 7) {
errorLabel.setText("Too many characters limit your characters to 7");
addInput.setText("");
for (int i = 0; i < balance.size(); i++) {
outputBox.setText(outputBox.getText() + balance.get(i) + "\n");
}
} else {
double list = Integer.parseInt(addInput.getText());
balance.add(list);
addInput.setText("");
//Setting the array list in outputbox
for (double i = 0; i < balance.size(); i++) {
outputBox.setText(outputBox.getText() + balance.get((int) i) + "\n");
errorLabel.setText("");
double sum = 0;
for (double j = 1; j < balance.size(); j++) {
sum += balance.get((int) j);
String converted = String.valueOf(sum);
errorLabel.setText("Your sum is " + (converted));
}
}
}
} catch (Exception e) {
errorLabel.setText("Error wrong characters.");
for (int i = 0; i < balance.size(); i++) {
outputBox.setText(outputBox.getText() + balance.get(i) + "\n");
}
}
}
The main problem is that you are starting your summation loop at 1
which is why the first index 0
get's skipped:
for(int j=0; j<balance.size(); j++){
sum += balance.get(j);
}
String converted = String.valueOf(sum);
errorLabel.setText("Your sum is " + (converted) );
Other sidenotes:
j
as a double
(and then cast it back to an int
) To make the whole thing cleaner, you can use a for-each
loop, since you don't need the index (and because ArrayList
is iterable)
for(double b: balance){ sum += b; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.