Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Can i limit how many times the same random integer is chosen?

Hi, I'm wondering if there is a way I can control how many times the same random integer is produced. For example, if I'm trying to produce numbers between 1-5, and I want to limit the amount of times that 5 can be chosen, to two. So, basically customize the amount of times each number is allowed to show up when producing them. Thanks to anyone that can answer me.

2 Answers

Just keep a count using an if statement.

int choosen5 = 0;

int nextNumber;
boolean getDifferentNumber;

do {
    getDifferentNumber = false;
    nextNumber = random.nextInt(5) + 1;
    if(nextNumber == 5) {
        choosen5++;
    }
    if(choosen5 > 3) {
        getDifferentNumber = true;
    }
while(getDifferentNumber);

Doh, haha, it looks so obvious now. Thanks, Logan.

Yep! No problem.