I'm trying to create my first android app here, and I'd stumbled upon a problem where I need to use the value of a variable between an if-else statement.
@Override
public void onClick(View view) {
int guess, x, y;
String st_bot, st_top;
if(view.getId() == R.id.btn_guess){
st_bot = bot.getText().toString();
st_top = top.getText().toString();
x = Integer.parseInt(st_bot);
y = Integer.parseInt(st_top);
guess = (x+y)/2;
tv_guess.setText(Integer.toString(guess));
} else if (view.getId() == R.id.btn_bigger){
st_bot = tv_guess.getText().toString();
//st_top = top.getText().toString();
guess = Integer.parseInt(st_bot);
//y = Integer.parseInt(st_top);
guess = (guess+y)/2;
tv_guess.setText(Integer.toString(guess));
} else if (view.getId() == R.id.btn_smaller){
//st_bot = bot.getText().toString();
st_top = tv_guess.getText().toString();
//x = Integer.parseInt(st_bot);
guess = Integer.parseInt(st_top);
guess = (x+guess)/2;
tv_guess.setText(Integer.toString(guess));
}
}
I want to pass the variable x and y from the R.id.btn_guess statement so that I can use it in the other states with the value that have been assigned previously. But when I do that, x and y showed to be not have been initialized.
When I try to make this in Java compiler (not android), the variables can be used in other statements without reassigning it.
What is the workaround of this? Thank you.