In: Computer Science
Class Design – IntList (A.k.a. ArrayList (v0.0))
Let’s build a useful class that wraps up an array of integers. This class will store two data items; one an array of integers, and the other a counter to track the number of actual elements in the list. Start by defining a new class called IntList and copying the main driver code included below or in IntList.java. Then, add each of the following functions and data items indicated in the member sections. The IntList.java file shows an example of a char list, be sure to change it to a list of integers in order to complete the assignment.
Data Members
Method Members
public static void main(String[] args) { IntList a = new IntList(); a.add(95); a.add(100); a.add(58); System.out.println(a.toString() ); //System.out.println(a.sum() ); //System.out.println(a.indexOf(100)); //uncomment these to work on next //System.out.println(a.indexOf(20)); //System.out.println(a.save() ); }
class IntList
{
//Declare a private integer array called “data ” with size 100
private int[] data=new int[100];
//Declare an integer called numElements
private int numElements=0;
//add() method add the value n to array data and add one to num_elements
public void add(int n)
{
//add the value n to array data
data[numElements]=n;
//add one to num_elements
numElements++;
}
//In a loop, append all the elements in our data array to this string, separated by a comma
public String toString() {
//Declaring loop variable i
int i;
//Declaring a string retVal to store the output string
String retVal="";
//Loop to access elements in array data
for(i=0;i<numElements;i++)
//Concatinating array elements to string
retVal+=" "+data[i];
//Return resulting string
return retVal;
}
//function to sum the integer elements stored in IntList
public int sum()
{
//Declaring integer variable sumElements to store sum of array elements
int sumElements=0;
//Declaring loop variable i
int i=0;
//Loop to access elements in array data
while(i<numElements)
{
//Add each element to sumElements
sumElements+=data[i];
//Incrementing loop variable
i++;
}
//Returning sum of array elements
return sumElements;
}
public int indexOf(int target)
{
//Declaring integer variable to store index of target variable
int index=-1;
//Declaring loop variable i
int i=0;
//Loop to access elements in array data
while(i<=numElements)
{
//Checking if array element is equal to value of target if yes set index=i and break from loop
if(data[i]==target)
{
index=i;
break;
}
//Incrementing loop variable
i++;
}
//Return index value
return index;
}
public static void main(String[] args)
{
IntList a = new IntList();
a.add(95); a.add(100); a.add(58);
System.out.println(a.toString() );
System.out.println(a.sum() );
System.out.println(a.indexOf(100)); //uncomment these to work on next
System.out.println(a.indexOf(20));
//System.out.println(a.save() );
}
}
Sample Output
Since there were no instructions for save() method it is not implemented