Results 1 to 3 of 3

Thread: Arrayindex [resolved]

  1. #1

    Thread Starter
    Dazed Member
    Join Date
    Oct 1999
    Location
    Ridgefield Park, NJ
    Posts
    3,418

    Arrayindex [resolved]

    Does anyone know why this would happen?
    When the first loop is excuted i get an ArrayIndexOutOfBounds
    exception. But the second loopruns fine.
    Code:
    public class Test{
            public static void main(String[] args){
               
             String s = new String("ABC"); 
             char[] c = new char[s.length()];         
             int[] intArray = new int[25]; 
           
             for(int i = 0; i < s.length(); i++){
                  c[s.charAt(i)]++; // array index out of bounds
             }
          
            for(int k = 0 ;k < s.length(); ++k){
              c[s.charAt(k)]++; // runs fine 
            }
      }
    }

  2. #2
    VirtuallyVB
    Guest

    Thumbs up

    char[] c = new char[s.length()];
    is equivalent to
    char[] c = new char[3];
    which declares 3 chars that are addressible by indicies 0,1,2.

    A=65
    B=66
    C=67

    so the first loop is trying to address 3 chars at indices 65,66,67.
    Since these indices do not exist in the char array named "c", these indices are out of bounds for this array.

    The code as is doesn't survive past the first exception, so I don't see what you mean by the second loop working out. I'd suspect the same error since 65,66,67 are not in the range 0-24.

    This may be related to you understanding the histogram code that counts integers.

  3. #3

Posting Permissions

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



Click Here to Expand Forum to Full Width