Results 1 to 4 of 4
  1. #1
    LasseA is offline Member
    Join Date
    Oct 2012
    Posts
    29
    Rep Power
    0

    Default Array method - printBackwards

    This code should produce the output of [424, 21, 9 ,5, 3, ]
    But it keeps showing the indexOutOfBoundsException.
    I know it's something inside my for loop, but I really can't figure out what's causing it.
    It should repeat 5 times, 0 < data.length is 5 times.
    Int J should be 4
    So the first data[j-i] should be 4 as well because 4-0 = 4, which is 424.
    What am I missing here?

    Java Code:
    public class SelfCheck11 {
    	public static void main(String[] args) {
    		int[] data = {3, 5, 9, 21, 424};
    		printBackwards(data);
    		
    	}
    	public static void printBackwards(int[] data) {
    		System.out.print("[ ");
    		for (int i = 0 ; i < data.length ; i++) {
    			int j = data[data.length-1];
    			System.out.print(data[j-i] + ", ");
    		}
    		System.out.print("]");
    	}
    }

  2. #2
    Estrella is offline Member
    Join Date
    Jan 2013
    Location
    Texas
    Posts
    16
    Rep Power
    0

    Default Re: Array method - printBackwards

    Java Code:
    int j = data[data.length-1];
    The line above does not assign 4 to j. Add a print statement after line 10 that prints out the value of j to see what is actually assigned to j.

  3. #3
    LasseA is offline Member
    Join Date
    Oct 2012
    Posts
    29
    Rep Power
    0

    Default Re: Array method - printBackwards

    Thanks! obviously it's just data.length-1, but sometimes you don't notice the small mistakes :)

  4. #4
    Estrella is offline Member
    Join Date
    Jan 2013
    Location
    Texas
    Posts
    16
    Rep Power
    0

    Default Re: Array method - printBackwards

    It happens! Glad I could help.

Similar Threads

  1. Array in Method Help
    By ETBunce in forum New To Java
    Replies: 2
    Last Post: 12-06-2012, 04:38 AM
  2. Need help with add method for array.
    By RozenKristal in forum New To Java
    Replies: 3
    Last Post: 10-15-2012, 04:38 AM
  3. I want to make an array in a method...
    By nhmllr in forum New To Java
    Replies: 7
    Last Post: 10-02-2011, 08:18 AM
  4. Array method problem
    By insanepenguin in forum New To Java
    Replies: 2
    Last Post: 12-04-2010, 04:58 PM
  5. Array Method Testing
    By Suzanne1187 in forum Java Applets
    Replies: 1
    Last Post: 04-15-2009, 08:23 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •