尝试创建BMI计算器我已经为重量和高度声明了一个变量,但我仍然得到“变量”重量的错误“可能尚未初始化。
public class MainActivity extends AppCompatActivity {
private EditText eheight, eweight;
private Button computeb;
private TextView output, category;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
eheight = (EditText) findViewById(R.id.eheight);
eweight = (EditText) findViewById(R.id.eweight);
output = (TextView) findViewById(R.id.output);
category = (TextView) findViewById(R.id.category);
computeb = (Button) findViewById(R.id.computeb);
computeb.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
float weight, height, BMI;
if (checkInputLength())
return;
weight = Float.parseFloat(weight.getText().toString());
height = Float.parseFloat(height.getText().toString());
computeBMI(weight, height);
BMI = weight / (height * height);
}
});
}
答案 0 :(得分:1)
weight.getText()? weight是一个浮点类型值,此处未初始化。我想你想用eweight。和身高一样。
weight = Float.parseFloat(eweight.getText().toString());
height = Float.parseFloat(eheight.getText().toString());
答案 1 :(得分:1)
更改
weight = Float.parseFloat(weight.getText().toString());
height = Float.parseFloat(height.getText().toString());
到
weight = Float.parseFloat(eweight.getText().toString());
height = Float.parseFloat(eheight.getText().toString());
权重和高度只是浮点变量。如果要解析来自edittext
的数据,则必须从edittexts获取数据并将它们存储在相应的变量中。
答案 2 :(得分:0)
将其设置为0。
float weight = 0;
答案 3 :(得分:0)
改变这个:
weight = Float.parseFloat(weight.getText().toString());
为:
weight = Float.parseFloat(eweight.getText().toString());