0

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.

1
  • Why do you want to achieve such a strange method? Is this really your question? Commented Jan 5, 2019 at 8:04

3 Answers 3

2

According to your variable name, I guess you are implementing a game like "Guess Big or Small".

You seems want to assign x and y in branch view.getId() == R.id.btn_guess, then use them in other two branch. If this is really what you need, just pull the declaration of x and y to outside the function, which let them have a wider variable scope, and keep them after onClick function ends at the first time.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use Integer class and set it to null or you can initialize the ints to 0

Comments

-1

Try to make lik below and see what happens.

int guess=0, x=0, y=0; String st_bot="", st_top="";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.