DawnDusk DawnDusk - 2 months ago 8
Android Question

Android - A variable might not have been initialized

Trying to create a BMI Calculator I already declared a variable for weight and height, but still I'm getting an error of "variable "weight" might not have been initialized.

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);
}
});
}

Answer

Change

weight = Float.parseFloat(weight.getText().toString());
height = Float.parseFloat(height.getText().toString());

to

weight = Float.parseFloat(eweight.getText().toString());
height = Float.parseFloat(eheight.getText().toString());

weight and height are just float variables.If you want to parse data from edittext then you have to get the data from the edittexts and store them in the corresponding variables.

Comments