How can I generate a random number in a certain range?

后端 未结 9 1871
抹茶落季
抹茶落季 2020-12-04 23:25

How can I create an app that generates a random number in Android using Eclipse and then show the result in a TextView field? The random number has to be in a r

9条回答
  •  暖寄归人
    2020-12-04 23:41

    To extend what Rahul Gupta said:

    You can use Java function int random = Random.nextInt(n).
    This returns a random int in the range [0, n-1].

    I.e., to get the range [20, 80] use:

    final int random = new Random().nextInt(61) + 20; // [0, 60] + 20 => [20, 80]
    

    To generalize more:

    final int min = 20;
    final int max = 80;
    final int random = new Random().nextInt((max - min) + 1) + min;
    

提交回复
热议问题