Difference between inclusive and exclusive?

前端 未结 2 1934
孤独总比滥情好
孤独总比滥情好 2021-01-15 06:38

I feel like it\'s a simple concept, but I\'m having trouble with inclusive and exclusive: particularly concerning random number generator.

For instance, if I wanted

2条回答
  •  天命终不由人
    2021-01-15 07:00

    For instance, if I wanted a value 2-8 (including 2 and 8), that would be inclusive, correct?

    Yes. Inclusive includes; Exclusive excludes.

    The range 2-8 inclusive is 7 unique values (2,3,4,5,6,7,8); and Random.nextInt(int) excludes the specified value. So you want something like

    Random rand = new Random();
    int min = 2;
    int max = 8;
    // ...
    int r = rand.nextInt((max - min) + 1) + min;
    

提交回复
热议问题