Your actual problem is a design problem. Your methods should do exactly one thing and one thing only. In this program, there are three things being done: checking the database for other accounts and inserting an account, while the third thing is checking for connections. Instead:
//This function checks to see if a user exists
public boolean userExists(Connection conn, String username) {
ResultSet rs = SQLOperations.getAllUser(connection);
while (rs.next()) {
String user=rs.getString("username");
if (username.equalsIgnoreCase(user)) {
return true;//This is the only thing we care about
}
}
return false;//We didn't find a duplicate username.
}
//This is our gateway function, but it actually is doing validation
public void insertNewUser(Connection conn, String username, String password, String confirmpassword) {
if (userExists(conn, username) { //Note this is our validation logic
System.out.println("Same username! Cannot add this account.");//probably should be an exception or return value, not println
} else { //we have validated the user, now validate password
if(!password.equals(cpassword)) {
System.out.println("not the same pass and cpass");
} else {
if (addUser(Connection conn, String username, String password)) {
System.out.println("Successfully added.");
} else {
System.out.println("Attempt to add user to db failed.");
}
}
}
} //note that we do nothing else in this function!
//Note this function assumes you've already run a validation check
private boolean addUser(Connection conn, String username, String password) {
if (connection != null) {//I think this is probably not the right place for this, but sure.
if (SQLOperations.addAccount(account, connection)) {
return true;
} else {
return true;
}
} else {
return false;
}
}
Note each function does exactly one thing (except for the last function, which should really be two functions or have intelligent exceptions to handle the dead connection case). By doing this you keep your code much cleaner. In fact, this code becomes even cleaner if you do use exceptions, and an exception-handling function. I highly recommend Clean Code as a book that will help you think more critically about this stuff.