skip to Main Content
String xxx = "Select Totalpay from payments2 where committee_member = '"+memberName+"'";
pst = conn.prepareStatement(xxx);
rs = pst.executeQuery();
while(rs.next()) {
    String totalPayment = rs.getString("TotalPay");
}

table.addCell(cell);
//String ttlpy = create();
table.addCell(totalPayment);

I get the error at table.addCell(totalPayment):

variable totalPayment may not have been initialized

How can I use the value of totalPayment outside while loop and print it on table.addCell()?

The code is inside a while loop which is giving the value of memberName in the sql query.

2

Answers


  1. If the loop never iterates (e.g. if no records are returned from the query), what value would you expect that variable to have and why?

    Declare it before the loop with a default value. For example:

    String totalPayment = "0";
    while (rs.next()) {
        totalPayment = rs.getString("TotalPay");
    }
    
    Login or Signup to reply.
  2. As you have declared the totalPayment variable inside the while loop it cannot be accessed outside, also you have to initialize the variable in-case the record is not found. As shown below :

    String xxx="Select Totalpay from payments2 where committee_member='"+memberName+"'";
    pst=conn.prepareStatement(xxx);
    rs=pst.executeQuery();
    String totalPayment="";      //changed code
    while(rs.next()){
        totalPayment=rs.getString("TotalPay");  //changed code
    }
    table.addCell(cell);
    //String ttlpy=create();
    table.addCell(totalPayment);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search