![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Newbie
Join Date: Nov 2005
Posts: 1
Rep Power: 0
![]() |
Sorting a Numeric Array
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;
}
}
}
}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! |
|
|
|
|
|
#2 |
|
Professional Programmer
|
When r you getting the array exception ? .... cause i don't receive that error.
__________________
Don't take life too seriously, it's not permanent ! |
|
|
|
|
|
#3 |
|
I eat cake for breakfast.
![]() ![]() ![]() ![]() Join Date: Jul 2004
Location: In my box.
Posts: 4,434
Rep Power: 8
![]() |
You can't print an array. You can print an array element though - perhaps what you wanted to do is loop through the array and print each element individually?
|
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|