Muhammad Faturrahman
Muhammad Faturrahman

Reputation: 21

I want to calculate data in jtable but i have a error [Java]

I want to multiply column 3 with column 4, and display it on the first line, but when I add the data in the next line, when doing the calculation again and display it on the second line, the data on the first line changes. This is my code, is there something wrong?

public int getCost() {
     int row = showTrans.getRowCount();
     int col = showTrans.getColumnCount();
     int cost;

     for (int i = 0; i < row; i++) {
        cost = Integer.parseInt(showTrans.getValueAt(i, 3).toString()) * 
               Integer.parseInt(showTrans.getValueAt(i, 4).toString());  

        String totalCost = String.valueOf(cost);
        model.setValueAt(totalCost, i, 4);           
     }

    return 0;
}

Upvotes: 0

Views: 60

Answers (1)

John Scattergood
John Scattergood

Reputation: 1042

The problem is that you are reusing column 4 for both cost and the total.

The first time it works because the cost is correct (total = 9460000), but the second time the cost is wrong because column 4 is now the total. As a result, it multiplies the quantity by the total cost (total = 9460000 * 2 = 18920000)

You need to use a new column for the total and everything should be fine.

Upvotes: 1

Related Questions