I have some data in JTable. I attempted to get sum of third column cell values, which matches with first column cell values are equal. As example T10. I can get only the existing values of third column not sum . I followed several answers in SO like,
CodePudding user response:
First, you have declared variable tWeights
inside the if-block, that is it's lifetime is limited to this block, you'll get a fresh tWeights
in every iteration when mark equals "T10".
Second, you use streams the wrong way and in this situation there's no advantage of using streams. Just sum it up iteratively:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model1 = (DefaultTableModel) jTable1.getModel();
BigDecimal tWeight = BigDecimal.ZERO; // let's start with 0 total weight
for (int i = 0; i < model1.getRowCount(); i ) {
String mark = (String) model1.getValueAt(i, 1);
if (mark.equals("T10")) {
BigDecimal weights = new BigDecimal((String) model1.getValueAt(i, 3));
tWeight = tWeight.add(weights); // add weight to tWeight and assign the result to tWeight
System.out.println(tWeight);
}
}
}
CodePudding user response:
Just another take on it. Maintains the listWeight
as well:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model1 = (DefaultTableModel) jTable1.getModel();
BigDecimal weights;
BigDecimal tWeight = new BigDecimal("0.0");
List<BigDecimal> listWeight = new ArrayList<>();
for (int i = 0; i < model1.getRowCount(); i ) {
String mark = model1.getValueAt(i, 1).toString();
if (mark.equals("T10")) {
weights = new BigDecimal(model1.getValueAt(i, 3).toString());
listWeight.add(weights);
tWeight = tWeight.add(weights);
// System.out.println("Growing Sum -> " tWeight);
}
}
// Display in Console Window...
System.out.println("Total sum of weights based on Size 'T10':");
StringBuilder formula = new StringBuilder("");
for (BigDecimal bdec : listWeight) {
if (!formula.toString().isEmpty()) {
formula.append(" ");
}
formula.append(bdec);
}
formula.append(" = ").append(tWeight);
System.out.println(formula.toString());
}