Need help with beginner java array program??
Assignment
This is a method that will rotate an array by a given number of positions,
d. If d is positive, the array rotates forward, if d is negative, the array rotates backwards. If d is zero, the array
is unchanged. For example. if the array a holds the elements 1, 4, 9, 16, 25, 36, after the call rotate(a, -
2) the values in a are 9, 16, 25, 36, 1, 4.
here is my code so far.
Code:
public class Rotater
{
private static int nums[]={1,2,3,4,5,6,7,8,9};
public static void main(String[] args)
{
printOut(nums);
rotate(nums,3);
printOut(nums);
rotate(nums,-4);
printOut(nums);
rotate(nums,0);
printOut(nums);
rotate(nums, -2);
}
public static void printOut(int[] a)
{
for(int x=0; x<a.length; x++)
{System.out.print(a[x]+" ");
System.out.println("\n");
}
}
public static void rotate(int a[], int d)
{
int temp=0;
if(d<0)
{
oneLeft(a);
}
else if(d>0)
{
oneRight(a);
}
}
private static void oneLeft(int a[])
{
int temp = a[1];
int temp2;
for(int j=a.length-1; j>=0; j++)
{
if(j==a.length-1)
{
temp=a[j-1];
a[j-1]=a[j];
}
else if(j==0)
{
a[a.length-1]=a[0];
}
else
{
temp2=a[j-1];
a[j-1]=temp;
temp=temp2;
}
}
}
private static void oneRight(int a[])
{
int temp = a[1];
int temp2;
for(int j=0; j<a.length; j++)
{
if(j+1>a.length-1)
{
a[0]=a[a.length-1];
}
else if(j==0)
{
temp=a[j+1];
a[j+1]=a[j];
}
else
{
temp2=a[j+1];
a[j+1]=temp;
temp=temp2;
}
}
}
}
Problem
when i try to run it highlites temp2=a[j-1]; from the program and says "java.lang.ArrayIndexOutOfBoundsException:9"
Re: Need help with beginner java array program??
Re: Need help with beginner java array program??
You shouldn't start another thread with the same problem as this one: http://www.java-forums.org/new-java/...gram-help.html
Quote:
"java.lang.ArrayIndexOutOfBoundsException:9"
Your array index is past the end of the array. Remember arrays are 0 based. The last index is the length-1.
Check your logic to see how the index got too large. If you can't see, add some println statement to print out the values of the variables as the code executes.
Also print out the size of the array.
Re: Need help with beginner java array program??
Let's keep this discussion all in one place. I'm closing this thread.
db