Skip to content

Instantly share code, notes, and snippets.

@ssaurel
Created November 28, 2016 09:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ssaurel/401b4f2f3270de4d2c3dff3ef0f09046 to your computer and use it in GitHub Desktop.
Save ssaurel/401b4f2f3270de4d2c3dff3ef0f09046 to your computer and use it in GitHub Desktop.
Java Code for a Simple BMI Calculator
package com.ssaurel.bmicalculator;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private EditText height;
private EditText weight;
private TextView result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
height = (EditText) findViewById(R.id.height);
weight = (EditText) findViewById(R.id.weight);
result = (TextView) findViewById(R.id.result);
}
public void calculateBMI(View v) {
String heightStr = height.getText().toString();
String weightStr = weight.getText().toString();
if (heightStr != null && !"".equals(heightStr)
&& weightStr != null && !"".equals(weightStr)) {
float heightValue = Float.parseFloat(heightStr) / 100;
float weightValue = Float.parseFloat(weightStr);
float bmi = weightValue / (heightValue * heightValue);
displayBMI(bmi);
}
}
private void displayBMI(float bmi) {
String bmiLabel = "";
if (Float.compare(bmi, 15f) <= 0) {
bmiLabel = getString(R.string.very_severely_underweight);
} else if (Float.compare(bmi, 15f) > 0 && Float.compare(bmi, 16f) <= 0) {
bmiLabel = getString(R.string.severely_underweight);
} else if (Float.compare(bmi, 16f) > 0 && Float.compare(bmi, 18.5f) <= 0) {
bmiLabel = getString(R.string.underweight);
} else if (Float.compare(bmi, 18.5f) > 0 && Float.compare(bmi, 25f) <= 0) {
bmiLabel = getString(R.string.normal);
} else if (Float.compare(bmi, 25f) > 0 && Float.compare(bmi, 30f) <= 0) {
bmiLabel = getString(R.string.overweight);
} else if (Float.compare(bmi, 30f) > 0 && Float.compare(bmi, 35f) <= 0) {
bmiLabel = getString(R.string.obese_class_i);
} else if (Float.compare(bmi, 35f) > 0 && Float.compare(bmi, 40f) <= 0) {
bmiLabel = getString(R.string.obese_class_ii);
} else {
bmiLabel = getString(R.string.obese_class_iii);
}
bmiLabel = bmi + "\n\n" + bmiLabel;
result.setText(bmiLabel);
}
}
@shahzad1
Copy link

What should be the units of height and weight?
Height = cm/ft?
Weight = kg/Lb?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment