1

I want to add the values of integer column "priority" obtained from the MySQL db by iterating resultset using while loop. My piece of code is as below:

    int TotalWestPriority = 0;
    int WestPty = 0;

    float lat = 0;
    float lon = 0;

    float Wb_SWLat = 0; // Currently holds some value from other process
    float Wb_NELat = 0; // Currently holds some value from other process
    float Wb_SWLon = 0; // Currently holds some value from other process
    float Wb_NELon = 0; // Currently holds some value from other process


//SQL Query:
    String qryVcl = "select priority, latitude, longitude from tbl_vcl";

    ResultSet Vp=stmt.executeQuery(qryVcl);

    while(Vp.next()){
        lat = Vp.getFloat("latitude");
        lon = Vp.getFloat("longitude");
        System.out.println("Total Lat received:"+lat);

        if(lat >=Wb_SWLat && lat <=Wb_NELat && lon>=Wb_SWLon && lon<=Wb_NELon){
            WestPty = Vp.getInt("priority");
            System.out.println("West Priority:"+WestPty);
        }
        }

Here, I'am able to print the result:-

West Priority:3

West Priority:2

I want to add those values and store in an integer.

how to add all the "westpty" from the iteration to "TotalWestPriority" ?

5
  • Hi, I just want to add the values coming out of while loop of the result set iteration and store in an integer. Any piece of code is highly appreciated and thanks in advance. Commented Dec 18, 2016 at 14:50
  • you mean you want to sum up the all values retrieved in every iteration like 3+2=5? Commented Dec 18, 2016 at 14:52
  • @PavneetSingh Yes, you are right Commented Dec 18, 2016 at 14:53
  • then it's too simple ,WestPty = WestPty +Vp.getInt("priority"); Commented Dec 18, 2016 at 14:55
  • @PavneetSingh I'll try. Thanks Commented Dec 18, 2016 at 14:57

1 Answer 1

3

Just accumulate them to another variable:

long total = 0L;
while (vp.next()) {
    lat = vp.getFloat("latitude");
    lon = vp.getFloat("longitude");

    if (lat >= Wb_SWLat && lat <= Wb_NELat && 
        lon >= Wb_SWLon && lon <= Wb_NELon) {

        westPty = Vp.getInt("priority");
        System.out.println("West Priority:"+WestPty);

        total += westPty;
    }
}

System.out.println("Total west priority: " + total);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.