I want to write the bmi calculation code in this program. When I specify variables "qad1" "vazn1" "bmi" "txtvazn" "txtqad" and "txtbmi" as final
, I encountered this error: "The final local variable cannot be assigned" And when I did not specify them as final
, I encountered this error: Cannot refer to the non-final local variable defined in an enclosing scope._ change modifier to final. I could not solve this problem with any trick.Please help me. The photo of the codes are uploaded here.Thank you.
public class Shakhes extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shakhes);
final EditText txtvazn=(EditText) findViewById(R.id.txtvazn);
final EditText txtqad=(EditText) findViewById(R.id.txtqad);
final TextView txtbmi=(TextView) findViewById(R.id.txtbmi);
Button btnbmi=(Button) findViewById(R.id.btnbmi);
final int qad1;
final int vazn1;
final float bmi;
btnbmi.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
qad1=Integer.parseInt(txtqad.getText().toString());
qad1=qad1/100;
vazn1=Integer.parseInt(txtvazn.getText().toString());
bmi=vazn1/(qad1*qad1);
txtbmi.setText(""+bmi);
}
});
}
}
You can define variables inside onClickListener
if use use them only inside listener:
( UPDATE as @DEADMC noted, final
is not required more in that case)
btnbmi.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
int qad1;
int vazn1;
float bmi;
// all other code
On the other hand, if scope of variable is more than listener, convert it to single-item array:
final int[] qad1 = new int[] {0};
btnbmi.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
qad1[0] = ...
}
}
Please take some read of immutability benefits in the first place (guess link http://okyasoft.blogspot.com/2014/05/6-benefits-of-programming-with_5146.html )
For your example, please try to make all the variable references you are trying to use under OnClickListener - as class fields (instead of method variables).
Defining, for example, txtbmi
as class member ( private TextView txtbmi;
) will automatically make it accessible to all the inner classes of your Shakhes
activity.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.