i have problem arranging the numbers from small to big. Im trying to overide the method of intlist in sortedinlist, the output i get is 0, 0,0. how can i fix this?
run:
0: 100
1: 50
2: 200
3: 25
0: 0
1: 0
2: 0
SortedIntList.java
public class SortedIntList extends IntList
{
public SortedIntList(int Size)
{
super(Size);
}
public void add(int value)
{
if (numElements == list.length)
System.out.println("Can't add, list is full");
else{
int empty = 0;
int f;
for(f=0;f<list.length-1;f++){
if(list[f] == 0)
{empty = f;}
}
list[empty] = value;
numElements++;
}
int k = 0; int temp = 0;
for(int i=0;i<list.length-1;i++)
{
k = i;
for(int j = i+1; j < list.length; j++)
{
if(list[j] < list[k])
k = j;
}
temp = list[k];
list[k] = list[i];
list[i] = temp;
}
}
}
ListTest.java
public class ListTest {
public static void main(String[] args)
{
IntList myList = new IntList(10);
myList.add(100);
myList.add(50);
myList.add(200);
myList.add(25);
System.out.println(myList);
SortedIntList myList2 = new SortedIntList(10);
myList2.add(20);
myList2.add(100);
myList2.add(30);
System.out.println(myList2);
}
}
IntList.java
public class IntList {
protected int[] list;
protected 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
{
list[numElements] = 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] + "\n";
return returnString;
}
}
Your problem is that you add the new numbers at the end of the total list. See this code (slightly reformatted)
Say your list is empty but can have 5 elements. This is what happens
However, if you now print your list it only prints the first element which is 0 since the inserted element is at the end of the list.
You probably want to break out of your loop early or nay check for actual number of elements, not how many elements could be in the list.