Results 1 to 2 of 2
  1. #1
    manibby93 is offline Member
    Join Date
    Sep 2013
    Posts
    77
    Rep Power
    0

    Default Array Index Out of Bounds Exception Error?? How can I get around it?

    I get this error:
    java.lang.ArrayIndexOutOfBoundsException: 10
    at TestCountLastDigits.main(TestCountLastDigits.java: 7)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Nativ e Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknow n Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Un known Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.ru nCommand(JavacCompiler.java:272)

    for this code:
    Java Code:
    public class TestCountLastDigits { 
    public static void main(String[] args) { 
    int[] numbers = { 9, 29, 44, 103, 2, 52, 12, 12, 76, 35, 20 }; 
    int[] element = countLastDigits(numbers); 
    
    for (int i = 0; i < numbers.length; i++) { 
    System.out.println(element[i]); 
    } 
    
    } 
    
    private static int[] countLastDigits(int[] numbers) { 
    int[] element = new int[10]; 
    
    for (int i : element) { 
    element[i] = 0; 
    } 
    
    for (int i : numbers) { 
    int digit = i % 10; 
    element[digit]++; 
    
    } 
    
    return element; 
    } 
    }
    Question: What can I do to avoid this error? THANKS.

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,810
    Rep Power
    5

    Default Re: Array Index Out of Bounds Exception Error?? How can I get around it?

    Your element array is of size 10. But you are passing in an array of size 11. And the latter is what you are using to index the former.

    If you want elements to be the same size as numbers, allocated the element array like this:
    Java Code:
    int [] element = new int[numbers.length];
    //
    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. array index out of bounds exception, AGAIN!
    By samanyu in forum New To Java
    Replies: 8
    Last Post: 06-08-2011, 12:27 PM
  2. Replies: 4
    Last Post: 01-31-2011, 09:20 PM
  3. Array Index Out Of Bounds Exception
    By manowar689 in forum New To Java
    Replies: 3
    Last Post: 06-19-2010, 12:25 AM
  4. array Index out of Bounds exception== 0
    By Allgorythm in forum New To Java
    Replies: 6
    Last Post: 02-11-2010, 05:02 PM
  5. Array Index Out of Bounds Exception
    By kool001 in forum New To Java
    Replies: 1
    Last Post: 12-03-2009, 08:42 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
  •