Created
November 28, 2016 09:34
-
-
Save ssaurel/401b4f2f3270de4d2c3dff3ef0f09046 to your computer and use it in GitHub Desktop.
Java Code for a Simple BMI Calculator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What should be the units of height and weight?
Height = cm/ft?
Weight = kg/Lb?