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!
Aucun commentaire:
Enregistrer un commentaire