0

I made a method for executing a array of values in Java. Whenever I try to run it, I end up with an ArrayOutOfBoundsException. My console points the error to being the "if" statement.

for (int i = 1; i <= array.length; i++) {
        if (array[i] instanceof String) {
            ps.setString(i, (String) array[i]);
        } else if (array[i] instanceof Integer) {
            ps.setInt(i, (int) array[i]);
        }
    }

I have no problem with the Connection or PreparedStatement from before. I only end up having problems with this method, because of the array(Object[]), is not working correctly. I use this method for inserting and deleting different data from "user" table. I take 4 parameters in here, first being ID(which is auto_generated and put as primary key. Second parameter is the name for my user, third is the users UUID and last one is the rank(kinda accesslevel) for the user. Im expecting that the first one(ID) does not count after it is auto_generated on every insert. So lets not count that with us. Here is a example of how I'm using the method:

executeQuery("INSERT INTO `user` (`name`, `uuid`, `rank`) VALUES (?, ?, ?)", new Object[]{"'username'", "'myUUID'", 64});

So after I have executed this method, I end up with an error telling me this:

java.lang.ArrayIndexOutOfBoundsException: 3
        at com.java.tarjeihs.plugin.mysql.MySQLAccessor.executeQuery(MySQLAccessor.java:107) ~[?:?]
        at com.java.tarjeihs.plugin.user.UserHandler.test(UserHandler.java:24) ~[?:?]

If you guys had problems understanding my explanation, please ask me for a better explanation.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
tarjeihs
  • 23
  • 3
  • possible duplicate of [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](http://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – BackSlash Mar 10 '15 at 15:29
  • **int i = 1; i <= array.length**: array[array.length] --> ArrayOutOfBoundsException – agad Mar 10 '15 at 15:31
  • Arrays are from 0 to length - 1, not from 1 to length. – David Conrad Mar 10 '15 at 15:49

1 Answers1

2

Array's indexes are zero based, and PreparedStament's are one based, so you're failing on an off-by-one issue:

for (int i = 0; i < array.length; i++) {
    if (array[i] instanceof String) {
        ps.setString(i + 1, (String) array[i]);
    } else if (array[i] instanceof Integer) {
        ps.setInt(i + 1, (int) array[i]);
    }
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350