Question

On this assignment, there isn't code for how to input "How many random integers should the...

On this assignment, there isn't code for how to input "How many random integers should the list contain?"

0 0
Add a comment Improve this question Transcribed image text
Answer #1

`Hey,

Note: Brother in case of any queries, just comment in box I would be very happy to assist all your queries

That has to mean using ArrayList<Integer>, since an ArrayList can't contain values of type int. The problem is pretty easy: Start with an empty list, then generate random integers and add them to the list until you have as many integers as you want. Since all the integers in the list must be different, before adding an integer to the list, we need to test whether that integer is already in the list. One way to do that is with the indexOf() method from the ArrayList class. If numbers is an ArrayList<Integer> and num is an int, then numbers.indexOf(num) returns -1 if num is not in the list. (Note that this relies on autoboxing to convert num into an object of type Integer, since indexOf() requires an object as its parameter.) To create the list of numbers, we just add integers to the list until it reaches the desired size. Assuming that count is the desired number of integers and max is the maximum allowed value for the integers, this can be done with

ArrayList<Integer> numbers = new ArrayList<Integer>();
while (numbers.size() < count) {
    int num = (int)(Math.random()*max) + 1;
    if ( numbers.indexOf(num) == -1 )
        numbers.add( num );
}

This code is the heart of the solution. There is one problem, however. If count > max, then it's impossible to get count different integers in the range from 1 to max, because there aren't that many different numbers in the range! In fact, the while loop will be an infinite loop in that case since the size of the ArrayList can never become larger than max. My solution avoids the infinite loop by throwing an IllegalArgumentException when count > max.

Kindly revert for any queries

Thanks.

Add a comment
Know the answer?
Add Answer to:
On this assignment, there isn't code for how to input "How many random integers should the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT