Hello everyone!
I am working on a small project for school with the following requirements:
- Create a program that requests the user to enter five integers
- Place these values into an array called
myArr
- Type any sorting method into this program that will sort the array
myArr
Here is my code:
public class CIS140Exam3Prog1
{
static BufferedReader keyboard =
new BufferedReader(new InputStreamReader(System.in));
//Main method
public static void main(String[] args) throws Exception
{
//declarations
int[] myArr = new int[5];
int i = 0;
// obtain user input and give the values to myArr[]
for (i = 0; i < myArr.length; i++)
{
System.out.print("Enter integer " + (i + 1) + ": ");
myArr[i] = Integer.parseInt(keyboard.readLine());
System.out.println("");
}
// print the contents of myArr[] before sorting
for (i = 0; i <= myArr.length - 1; i++)
System.out.println(myArr[i]+" ");
System.out.println();
System.out.println("After calling the sorting method \n");
// the following line is causing the out of bounds exception
insertionSort(myArr, myArr.length);
// another attempt at sorting myArr[]
Arrays.sort(myArr, myArr.length - 1, myArr.length);
System.out.println(myArr); // this line displays a hash code
}
// insertion sort method
public static void insertionSort(int[] list, int listLength)
{
{
int frstOutOfOrder, location, temp;
for (frstOutOfOrder = 0; frstOutOfOrder < listLength; frstOutOfOrder++)
if (list[frstOutOfOrder] < list[frstOutOfOrder] - 1)
{ temp = list[frstOutOfOrder];
location = frstOutOfOrder;
do
{ list[location] = list[location - 1];
location--;
}
while (location > 0 && list[location - 1] > temp);
list[location] = temp;
}
}
}
} This is the exception I am getting:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at eldervaleriecis140.CIS140Exam3Prog1.main(CIS140Exam3Prog1.java:30)
I am lost =(
Any help or suggestions would be much appreciated!