我想在单击按钮时生成一个随机数,但是变量超出范围。我该如何解决?

时间:2019-06-08 20:37:00

标签: java android android-developer-api

我正在尝试在android studio上制作一个应用。我有一个按钮,按下时应生成一个新的随机数。如何将新生成的号码传递给代码?

public class MainActivity extends AppCompatActivity {

    Random rand = new Random();

    public void NewNumOnClick (View view){
    int RandomNumberGenerated = 1+ rand.nextInt(20);

    }


    public void GuessOnClick(View view){
        EditText numberGuessed = (EditText) findViewById(R.id.numberGuessedET);
        int input = Integer.parseInt(numberGuessed.getText().toString());
        Log.i("Status : " , "The user entered " + input);

        if (input > 20 || input < 1){
            Toast.makeText(this,"The number you entered is out of range. Please enter #1-20", Toast.LENGTH_LONG).show();
        }

        if (RandomNumberGenerated == input){
            Toast.makeText(this,"YOU GUESSED IT RIGHT!", Toast.LENGTH_LONG).show();
        }

        if(input > RandomNumberGenerated){
            Toast.makeText(this,"Try a lower number", Toast.LENGTH_LONG).show();

        }
        if (input < RandomNumberGenerated)
            Toast.makeText(this,"Try a higher number", Toast.LENGTH_LONG).show();



    }

RandomNumberGenerated变量是GuessOnClick函数未知的。如何使用指针?这样可以解决问题吗?

1 个答案:

答案 0 :(得分:1)

只需在活动中将int RandomNumberGenerated声明为字段成员变量

 public class MainActivity extends AppCompatActivity {
      Random rand = new Random();
      int mRandomNumberGenerated;
      ...........