This lab is very simple and intended to get you back into the swing of Java programming.
Recall that the number of elements an array has must be specified when you create it and cannot be changed later. However, in many situations, it is impossible to know in advance how many elements will actually be needed. In such cases, the only solution is to allocate an array large enough to handle the worst-case scenario and to then use a subset of its elements as needed. There are various ways to specify the subset, the most common of which is to store data values sequentially from the beginning of the array and to maintain a count of the number of such data values, thus making it easy to ensure that only those elements that contain valid data are processed. The following exercises ask you to create a class that can hold a varying number of integer values and to use this to solve a number of simple problems.
Design and implement a class, IntBag, that allows a variable sized collection of integer values to be stored. Your class should have two properties,
bag that will hold the values of the collection, and valid that says how many of the elements of bag actually contain values in the collection. The values themselves must be stored in the first valid elements of the bag. The class should have two constructors,
Provide methods to,
i within it, String representation of the collection (method must be named toString), i in the collection.
Design & implement a program to efficiently compute & display the first 100 prime numbers, making use of the fact that a number is prime if and only if it is not divisible by any prime less than itself. Use an instance of your IntBag class to keep a collection of primes found so far. Initially it should contain only the number 2 (the first prime). Generate and check candidate values sequentially from 3 onwards, adding any value found to be prime to the collection, until the number of values in the collection is 100. Efficiently check whether a candidate value is prime by attempting to divide it by each of the values in the collection.
Add a method to your IntBag class that returns the locations (indexes) of all instances of a given value in the collection. To demonstrate and test this method, write a program that presents the user with a menu having the following options (which can be selected in any order by typing the corresponding number):
Note about menu options 6, 7 & 8: