-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainActivity.java
87 lines (65 loc) · 2.41 KB
/
MainActivity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
//Import necessary package and file
package com.example.bmi;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
//Main activity class start here
public class MainActivity extends Activity {
//Define layout
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the references to the widgets
final EditText e1 = (EditText) findViewById(R.id.et1);
final EditText e2 = (EditText) findViewById(R.id.et2);
final TextView tv4 = (TextView) findViewById(R.id.tv4);
findViewById(R.id.ib1).setOnClickListener(new View.OnClickListener() {
// Logic for validation, input can't be empty
@Override
public void onClick(View v) {
String str1 = e1.getText().toString();
String str2 = e2.getText().toString();
if(TextUtils.isEmpty(str1)){
e1.setError("Please enter your weight");
e1.requestFocus();
return;
}
if(TextUtils.isEmpty(str2)){
e2.setError("Please enter your height");
e2.requestFocus();
return;
}
//Get the user values from the widget reference
float weight = Float.parseFloat(str1);
float height = Float.parseFloat(str2)/100;
//Calculate BMI value
float bmiValue = calculateBMI(weight, height);
//Define the meaning of the bmi value
String bmiInterpretation = interpretBMI(bmiValue);
tv4.setText(String.valueOf(bmiValue + "-" + bmiInterpretation));
}
});
}
//Calculate BMI
private float calculateBMI (float weight, float height) {
return (float) (weight / (height * height));
}
// Interpret what BMI means
private String interpretBMI(float bmiValue) {
if (bmiValue < 16) {
return "Severely underweight";
} else if (bmiValue < 18.5) {
return "Underweight";
} else if (bmiValue < 25) {
return "Normal";
} else if (bmiValue < 30) {
return "Overweight";
} else {
return "Obese";
}
}
}