-1

i am trying to understand logic behind instance variables scope in this case :

 public class DiceActivity extends AppCompatActivity implements View.OnClickListener {

private TextView textResult;
private int max;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dice);

    int max = getIntent().getIntExtra("max", 0);


    TextView textTitle = (TextView) findViewById(R.id.textTitle);
    textTitle.setText(max+" sided dice");

    textResult = ((TextView) findViewById(R.id.textResult));
    textResult.setText("");
    Button buttonRoll = (Button) findViewById(R.id.buttonRoll);
    buttonRoll.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    SecureRandom random = new SecureRandom();
    int result = random.nextInt(max) + 1;
    textResult.setText(String.valueOf(result));
}

}

the instance variable "max" is not linked to "max" in onCreate method (max returns 0 unless i declare max2=max to get correct result) but somehow textResult works well and doesn t need to declare another variable to get the result.

sheva
  • 1
  • 1
  • When you declared `int max` in onCreate, you create a new variable. It's called "shadowing". Both variables exist and have the same name, but only the one from the innermost scope is accessible. If you just want to access the outer one, you can do `this.max`, or just don't redeclare it. – Nicolas May 03 '20 at 21:20
  • https://stackoverflow.com/questions/42117386/why-are-my-fields-initialized-to-null-or-to-the-default-value-of-zero-when-ive – Sotirios Delimanolis May 03 '20 at 21:21

1 Answers1

0

Because you are using int twice!

It should be like this:

max = getIntent().getIntExtra("max", 0);
Ticherhaz FreePalestine
  • 2,738
  • 4
  • 20
  • 46