I'm making a program that will add values to an array and then sort the values, however, i have to do it under the same method and i cannot use Arrays.sort. I feel like my code makes perfect sense but it isn't changing any part of the array for some reason.
Here's my class file:
public class IntList { int[] list; private int[] tempArray; private int numElements = 0; private int temp=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++; } for (int i = 0 ; i < numElements; i++) { if (list[i] > list[i+1]) { temp = list[i]; list[i] = list[i+1]; list[i] = temp; } } } //------------------------------------------------------------- // 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; } }
Here's the main:
public class ListTest { public static void main(String[] args) { IntList myList = new IntList(10); myList.add(84); myList.add(27); myList.add(250); myList.add(18); myList.add(94); myList.add(8); myList.add(87); System.out.println(myList); } }