AlphaProgrammer AlphaProgrammer - 6 months ago 10
Java Question

how to get value by reference of count using java

public boolean addPeerReview(String courseid, String studentname, String ratings, String feedback, String reviewerName) {

boolean flag = false;
PreparedStatement pst = null;
try {
pst = con.prepareStatement("INSERT into PEERREVIEW (courseid,studentname,ratings,feedback,reviewerName) VALUES(?,?,?,?,?)");
pst.setString(1, courseid);
pst.setString(2, studentname);
pst.setString(3, ratings);
pst.setString(4, feedback);
pst.setString(5, reviewerName);
if (i <= 2) {
if (pst.executeUpdate() > 0) {
flag = true;
i++;
}
else{
flag=false;
}
}

} catch (SQLException ex) {
}
return flag;
}


Above is my code.I call it in this servlet(basically this adds records to DB)

int count =0;
if(peerreview.addPeerReview(courseid, studentname, rating, feedback, reviewerName)){

message = "Peer review successfull!";
request.setAttribute("message", message);
rd = request.getRequestDispatcher("peerreview.jsp");
rd.forward(request, response);
count++;

}


I want only two records to be added to the database(the scenario is students should be able to do a peer review for two other students).Therfore,i am using a count, however when i run the method again,since java is pasing by value and not reference the count always starts from 0 when i call the method again,instead of starting from 1.Is there any solution for my problem?

Answer

How about using :

static int count

The static modifier is used to create variables and methods that will exist independently of any instances created for the class.

All static members exist before you ever make a new instance of a class, and there will be only one copy of a static member regardless of the number of instances of that class.

In other words, all instances of a given class share the same value for any given static variable.