I really have no idea what to do. Would someone please help me with this? File I
ID: 3546100 • Letter: I
Question
I really have no idea what to do. Would someone please help me with this?
File IntList.java contains code for an integer list class. Save it to your directory and study it; notice that the only things you can do are to create a list of a fixed size and add an element to a list. If the list is already full, a message will be printed.
File ListTest.java contains code for a class that creates an IntList, puts some values in it, and prints it. Save this to your directory and compile and run it to see how it works.
Now modify the add method in IntList.java such that its elements should always be in sorted order from smallest to largest. This means that when an element is inserted into a IntList it should be put into its sorted place, not just at the end of the array. To do this you'll need to do two things when you add a new element:
Explanation / Answer
// IntList.java
public class IntList {
private int[] list;
private int numElements = 0;
//-------------------------------------------------------------
// Constructor -- creates an integer list of a given size.
//-------------------------------------------------------------
public IntList(int size)
{
list = new int[size];
}
//------------------------------------------------------------
// Adds an integer to the list. If the list is full,
// prints a message and does nothing.
//------------------------------------------------------------
public void add(int value)
{
if (numElements == list.length)
System.out.println("Can't add, list is full");
else
{
int i=0;
for( ; i<numElements ; i++)
{
if(value < list[i] ){
for(int j=numElements;j>i;j--){
list[j] = list [j-1];
}
break;
}
}
list[i] = value;
numElements++;
}
}
//-------------------------------------------------------------
// Returns a string containing the elements of the list with their
// indices.
//-------------------------------------------------------------
public String toString()
{
String returnString = "";
for (int i=0; i<numElements; i++)
returnString += i + ": " + list[i] + " ";
return returnString;
}
}