-2

I am trying to make an app on android studio. I have a button, when pressed should generate a new random number. How do I pass my new generated number to my code?

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 variable is unknown to the GuessOnClick funtion. How do i use pointers? will that fix the problem?

Zoe
  • 27,060
  • 21
  • 118
  • 148
  • Java doesn't support pointers. – Zoe Jun 08 '19 at 20:37
  • Make `RandomNumberGenerated` a field on the `MainActivity` class, rather than a local variable. Then, other methods in that class can reference it. (Also, Java conventions are to start variable and field names with a lowercase: `randomNumberGenerated`.) – yshavit Jun 08 '19 at 20:41
  • Seriously, you know how to do object member `Random rand` but do not know how can a variable be shared across different scopes. [Learn how to walk before trying to run, Java Tutorial](https://www.w3schools.com/java/java_class_attributes.asp) – Valen Jun 08 '19 at 21:47
  • Possible duplicate of [Class Members -- Java vs. Python](https://stackoverflow.com/questions/37600192/class-members-java-vs-python) – Valen Jun 08 '19 at 21:52

1 Answers1

1

Just declare int RandomNumberGenerated as field or member variable in the activity

 public class MainActivity extends AppCompatActivity {
      Random rand = new Random();
      int mRandomNumberGenerated;
      ...........
Santanu Sur
  • 10,997
  • 7
  • 33
  • 52