0

I am trying to see the contents of an array, but when I run it comes an error message

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 101

Does anyone know where the problem is? here is my code:

public final class KonversiQtoH extends DebitDiberikan{

public KonversiQtoH() throws SQLException{
    QBeriPintu1();
}
Connection c = KoneksiDatabase.getKoneksi();
Float[] fine;
public void QBeriPintu1() throws SQLException{
    try{
        List rowValues = new ArrayList();
        Statement s = c.createStatement();
        String sql = "SELECT LA40 from tabel_debit";
        ResultSet rs = s.executeQuery(sql);
        while (rs.next()){
            rowValues.add(rs.getFloat("LA40"));
        }
        rs.close();
        s.close();
        fine = (Float[]) rowValues.toArray(new Float[rowValues.size()]);
    }catch(SQLException e){
        System.err.println("QKanan, error");
    }
}
public static void main(String[] args) throws SQLException{
    KonversiQtoH j = new KonversiQtoH();
    j.QBeriPintu1();
    for (int i=0; i<=j.fine.length; i++){
        int a = i+1;
        System.out.println(a+". "+j.fine[i]);
    }
}
}
adjieq
  • 99
  • 1
  • 11
  • seems to be a duplicate of http://stackoverflow.com/q/5554734/754550 – miracle173 May 18 '17 at 03:46
  • check your `main` method in loop you used `<=` which means greater than equals to the length of array. but index is accessible to `length-1` – Vikrant Kashyap May 18 '17 at 03:48
  • 2
    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) – P.J.Meisch May 18 '17 at 03:49

4 Answers4

2

The following line produces errors:

for (int i=0; i<=j.fine.length; i++) {

Replace with:

for (int i=0; i<j.fine.length; i++) {
dat3450
  • 954
  • 3
  • 13
  • 27
1

This appears to be the problematical code:

for (int i=0; i <= j.fine.length; i++) {
    int a = i+1;
    System.out.println(a+". "+j.fine[i]);
}

Arrays in Java are indexed from zero to the length minus one. The above loop actually tries to access one beyond the length of the array. Fixing the bounds should get rid of this error:

for (int i=0; i < j.fine.length; i++){
    int a = i+1;
    System.out.println(a+". "+j.fine[i]);
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

Change here

for (int i=0; i<=j.fine.length; i++){
        int a = i+1;
        System.out.println(a+". "+j.fine[i]);
    }

to

for (int i=0; i<j.fine.length; i++){
        int a = i+1;
        System.out.println(a+". "+j.fine[i]);
    }

Comparison operatore from <= to <

Maxim Tulupov
  • 1,621
  • 13
  • 8
1

You should remove the "=" i<=j.fine.length

for (int i=0; i<j.fine.length; i++){
    int a = i+1;
    System.out.println(a+". "+j.fine[i]);
}