由于某些原因,我的输入验证不起作用。每次我把calculate放在“app”上,当它应该有一个错误,说我需要输入身高/体重时,它就会崩溃。当我输入数字时,它会计算。谢谢你的帮助:)。我是新来安卓工作室的。
这是我的计算java文件
public class BmiFrag extends Fragment implements View.OnClickListener {
Button BmiButton;
private double weight1=0;
private double height1=0;
public static EditText heightIn;
public static EditText weightIn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.fragment_bmi, container, false);
BmiButton = (Button) myView.findViewById(R.id.CalculateBmi);
BmiButton.setOnClickListener(this);
return myView;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.CalculateBmi:
weightIn = (EditText)
getActivity().findViewById(R.id.ETtweight);
heightIn = (EditText) getActivity().findViewById(R.id.ETHeight);
final TextView tv4 = (TextView)
getActivity().findViewById(R.id.TFDisplayBmi);
String str1 = weightIn.getText().toString();
String str2 = heightIn.getText().toString();
float weight = Float.parseFloat(str1);
float height = Float.parseFloat(str2) ;
float bmiValue = calculateBMI(weight, height);
String bmiInterpretation = interpretBMI(bmiValue);
tv4.setText(String.valueOf(bmiValue + "-" + bmiInterpretation));
if (TextUtils.isEmpty(str1)) {
weightIn.setError("Please enter your weight");
weightIn.requestFocus();
return;
}
else if (TextUtils.isEmpty(str2)) {
heightIn.setError("Please enter your height");
heightIn.requestFocus();
return;
}
break;
}
}
private float calculateBMI(float weight, float height) {
float bmi= (float) (weight/ (height*height)*4.88);
float total= Math.round(bmi);
return total;
}
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";
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public void onDestroy() {
}
@Override
public void onDetach() {
super.onDetach();
}
}
3条答案
按热度按时间q9yhzks01#
试着像下面这样修改代码,
ebdffaop2#
zzlelutf3#
首先,整理缩进和变量名。从不命名变量str1,str2:总是有意义的名称。压痕应始终保持一致。这将有帮助,但在未来的可读性和速度固定。
在您实际输入并通过
calculateBMI() method
这部分代码是这样写的:让我们从文本字段中提取文本,解释bmi,然后查看文本字段是否为空