Results 1 to 4 of 4
- 01-31-2012, 03:14 AM #1
Member
- Join Date
- Jan 2012
- Posts
- 3
- Rep Power
- 0
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.
ProblemJava 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; } } } }
when i try to run it highlites temp2=a[j-1]; from the program and says "java.lang.ArrayIndexOutOfBoundsException:9"Last edited by Norm; 01-31-2012 at 03:35 AM. Reason: added code tags
- 01-31-2012, 03:29 AM #2
Re: Need help with beginner java array program??
double post ?
- 01-31-2012, 03:39 AM #3
Re: Need help with beginner java array program??
You shouldn't start another thread with the same problem as this one: Java rotater program help
Your array index is past the end of the array. Remember arrays are 0 based. The last index is the length-1."java.lang.ArrayIndexOutOfBoundsException:9"
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.
- 01-31-2012, 08:24 AM #4
Similar Threads
-
Triangle program for beginner
By shawnx715 in forum New To JavaReplies: 18Last Post: 11-15-2011, 12:40 PM -
Help with beginner Java program? Boolean?
By katiebear128 in forum New To JavaReplies: 20Last Post: 09-30-2011, 06:35 PM -
Java Beginner: Can't Figure out Loop Array Issue.
By CMDR Reservoir in forum New To JavaReplies: 4Last Post: 07-19-2011, 02:30 AM -
JAVA Beginner - Simple Program help
By Logik22 in forum New To JavaReplies: 13Last Post: 07-15-2011, 02:44 PM -
Beginner Needs Help w/ Program for School
By badness in forum New To JavaReplies: 2Last Post: 11-24-2007, 07:51 PM


LinkBack URL
About LinkBacks

Bookmarks