1

This should've been simple, I wanted to retrieve KATA records from KATA_DASAR table and put it into an array named kamusKata[]. But I cannot seem to write the correct code, any help? Thank in advance. :)

package ir;

import java.sql.*;

public class kataDasar {
private String[] kamusKata;
private int i=0;

public kataDasar () {
    try {
            //definisi connection
            Connection con = DriverManager.getConnection( "jdbc:derby://localhost:1527/stemming", "admin", "admin" );
            Statement stmt = con.createStatement( );
            //SQL query 
            String SQL = "SELECT KATA FROM KATA_DASAR";
            ResultSet rs = stmt.executeQuery(SQL);

            while (rs.next()){
            String hasil = (rs.getString("KATA"));
            setKamusKata(hasil);
            }

        } catch (SQLException ex) {
            System.err.println("Connection failed"); //jika connection failed
        }
};

private void setKamusKata (String kata) {
    kamusKata[i] = kata;
    i++;
}

public String getKamusKata () {
    return kamusKata;
}
}
1
  • Can I have some more detail on the type of data in that database column and what is the contents of the kamusKata array after the constructor finishes execution? Commented May 2, 2012 at 20:28

2 Answers 2

3

See: ArrayList http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html

trutheality's answer probably won't help you because you're never initializing your array.

You would do something like this:

kamusKata = new ArrayList<String>();

while(rs.next()) {
 kamusKata.add(rs.getString('KATA')
}

but I'm not sure what your getKamusKata() method is supposed to do. If you want to return it as a string you should look at this question: Java equivalents of C# String.Format() and String.Join()

alternately have your method do:

StringBuilder sb=new StringBuilder();
for(string kata : kamusKata) {
   sb.append(kata);
}

return sb.toString();
Sign up to request clarification or add additional context in comments.

Comments

0

This:

public String getKamusKata () {
    return kamusKata;
}

is probably the problem. Your method should return a String but you're trying to return a String[].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.