Search code examples
javadatabasecucumberresultset

How to retrieve values from Result set and use it for calculations


I am using cucumber with Java and I want to calculate the tax. To do so I am connecting to data base and fetching the Gross Amount from data base. Below are the Gross pension values which result set has returned

248.36, 125.36,452.36,578.35,456.77,

But now tax is getting calculated only for last value i.e, 456.77.I want to calculate tax for all the values. How do I do it? Below is the code which I have tried

while(rs.next()) {
    //To retrieve the first column
    GrossPension = rs.getFloat("GrossPension");             
    log.info("GrossPension is :" +GrossPension);
    float tax = this.GrossPension/5;        
    System.out.println("Tax is: "+tax);     
}

GrossPension = rs.getFloat("GrossPension"); has retrieved values 248.36, 125.36, 452.36, 578.35, 456.77


Solution

  • You should do it as follows:

    List<Float> grossPensionList = new ArrayList<Float>();
    float grossPension;
    while(rs.next()) {
        //To retrieve the first column
        grossPension = rs.getFloat("GrossPension");             
        log.info("GrossPension is :" +grossPension);
        grossPensionList.add(grossPension/5);        
     }
    
    for (float tax: grossPensionList){
        System.out.println(tax);
    }
    

    The logic is to add gross pension retrieved from each row to a list and display the list once all the rows are read.