• Post Reply Bookmark Topic Watch Topic
  • New Topic

Coding Bat Woes  RSS feed

 
Laura Tobin
Greenhorn
Posts: 18
Eclipse IDE Java Postgres Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello lovely people,

So I am working on my CodingBat as I need massive practice before I attempt to head back into the immersion course I was in before.
I'm in Array-1 now and I'm getting this when I work on the problem called CommonEnd:

Exception:java.lang.ArrayIndexOutOfBoundsException: 3 (line number:6)

I get it on 3 of the 5 returns.

Here is my code:

public boolean commonEnd(int[] a, int[] b) {

if ( a[0] == b[0] || a[a.length]-1 == b[b.length]-1)
return true;
else return false;

}

I think I know where I'm off base, but I'm not sure how to fix it. It seems like it doesn't know how big the array is supposed to be. So I tried declaring the array sizes first. Then I tried declaring them inside the if statement before the length check. Still no good.

I know if I was writing this from scratch I'd be checking the console but when I do that on CodingBats it doesn't make any sense to me.

Help?


 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch, Laura.

ArrayIndexOutOfBoundsException means that you are trying to access an array element with an invalid index. If you have an array with N elements, then valid indices are 0 upto N - 1. If your index is less than 0 or greater than N - 1, then you will get this exception.

In your code, you're doing: a[a.length] - 1 and b[b.length] - 1

a.length is an invalid index for array a. Valid indices are 0 to a.length - 1.

You probably meant to write: a[a.length - 1] instead of a[a.length] - 1, and the same for array b.
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nothing to do with your problem, but the code block

can be more simply written as

 
Laura Tobin
Greenhorn
Posts: 18
Eclipse IDE Java Postgres Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh man! One little bracket... *facedesk*

Thank you so much!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!