JJ___
JJ___

Reputation: 207

Get the random value inside for loop

What I'm doing here is trying to generate a number and see whether it is the same as a number in the array. If it is same, the system will regenerate until the number is unique.

Random randomno = new Random();
int r = randomno.nextInt(3);

TextView randomnumber = (TextView) findViewById(R.id.TVRno);

int[] arr = new int[2];
arr[0] = 0;
arr[1] = 2;

for(int i = 0; i < arr.length; i++){
    if(r == arr[i]){
        z = randomno.nextInt(3);
        i = 0;
    }
}

randomnumber.setText("" + z);

But in the end I could not print the variable z in the for loop. How do I print the variable z? Am I using the wrong method to do this?

Upvotes: 0

Views: 94

Answers (1)

user4531029
user4531029

Reputation:

The variable z here is out of scope. It's what's called a block variable and it can only be accessed from within the loop. To access it outside, it needs to be declared outside of that loop:

Random randomno = new Random();

int r = randomno.nextInt(3);

TextView randomnumber = (TextView) findViewById(R.id.TVRno);

int[] arr = new int[2];

arr[0] = 0;

arr[1] = 2;

int z = 0;

            for(int i = 0; i < arr.length; i++){
                if(r == arr[i]){
                    z = randomno.nextInt(3);
                    i = 0;
                }
            }
randomnumber.setText("" + z);

Looking again, it doesn't seem that you EVER initialized z, inside or out. Was your code crashing? If so, that's why.

Side note: You can initialize that array like this: int arr = new int[] {0,20};

Upvotes: 1

Related Questions