#169 Code Review of a BMI Calculation Service
Perform a code review:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class PersonService {
/**
* Returns the average body mass index of all male persons over 18
*
* @return
*/
public void getAdultMaleUsersAverageBMI() {
double totalImt = 0.0;
long countOfPerson = 0;
double heightInMeters = 0d;
double imt = 0d;
List<Person> adultPersons = new ArrayList<>();
try {
Connection c = DriverManager.getConnection("jdbc:hsqldb:mem:test", "admin", "qwerty$4");
Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT * FROM person WHERE sex = 'male' AND age > 18");
while (rs.next()) {
Person p = new Person();
// Retrieve by column name
p.setId(rs.getLong("id"));
p.setSex(rs.getString("sex"));
p.setName(rs.getString("name"));
p.setAge(rs.getLong("age"));
p.setWeight(rs.getLong("weight"));
p.setHeight(rs.getLong("height"));
adultPersons.add(p);
}
for (Person p : adultPersons) {
heightInMeters = p.getHeight() / 100d;
imt = p.getWeight() / (Double) (heightInMeters * heightInMeters);
totalImt += imt;
}
countOfPerson = adultPersons.size();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Average imt - " + totalImt / countOfPerson);
}
}
class Person {
private Long id;
private String sex;
private String name;
private Long age;
private Long weight;
private Long height;
}
Question review
Sign in to start the dialogue
The mentor keeps the context of the current question and your previous messages.
Sign in
Available with Premium
This is just one of the solutions available with Premium. And more:
- 250+ advanced lectures
- 1300+ practice exercises
- 500+ solutions to problems from real interviews
- Personalized Java Hub certificates
- Expanded access to the AI mentor