dcvman dcvman - 1 month ago 10
Android Question

Random integer declared in onCreate

I am new in this community and sorry if my question does not meet the policy, I will try my best to improve for my next questions.

I am currently learning Android, I have good bases in Java.

I try to use the following code in onCreate to get a random integer (1-20):

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

int randomNumber = (int)(Math.random()*20)+1;

}


And on my MainActivity class:

public class MainActivity extends AppCompatActivity {
int randomNumber;


It does not work, I get only 0 as random number.

However if I do not declare my random integer on onCreat but only in Mainactivity, it works:

public class MainActivity extends AppCompatActivity {
int randomNumber=(int)(Math.random()*20)+1;


Finally if I use another way to get a random number declared on the onCreate, it Works as shown below:

public class MainActivity extends AppCompatActivity {
int randomNumber;

....

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random rand = new Random();
randomNumber=rand.nextInt(20)+1;
}
}


I do not understand why I could not declare my random in the onCreate method. with Math.random but worked with rand.nextInt Anyway, I was able to make it using other code but I would like to understand why.

onClick method code were not shown.

Thanks a lot for your help!

Answer Source

There is the problem in your code. You are using a variable 'randomNumber' as a global variable. but in oncreate method you are creating another variable with the same name 'randomNumber'. That means random number which you are obtaining is actually stored in local variable rather in global variable. And for your question

It does not work, I get only 0 as random number.

This is happening because global int variable is not local variable but instance variable by default instance variable is initialized with 0. I hope I answer the question.