为什么在安卓 Java 中,变量类在这种情况下没有被实现?

huangapple 未分类评论46阅读模式
英文:

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);

huangapple
  • 本文由 发表于 2020年5月4日 05:18:56
  • 转载请务必保留本文链接:https://java.coder-hub.com/61581763.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定