英文:
Why in android java variable class is not implemented 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);
max = getIntent().getIntExtra("max", 0);
TextView textTitle = (TextView) findViewById(R.id.textTitle);
textTitle.setText(max + " 面骰子");
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));
}
}
请注意,我只翻译了你提供的代码部分,不包括额外的内容。
英文:
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.
答案1
得分: 0
因为你两次使用了int
!
应该像这样:
max = getIntent().getIntExtra("max", 0);
英文:
Because you are using int
twice!
It should be like this:
max = getIntent().getIntExtra("max", 0);
专注分享java语言的经验与见解,让所有开发者获益!
评论