Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - return array from method

I created this snippet:

public static String[] get_data()
{
    conn = getInstance();
    String[] data_array = null;
    if(conn != null)
    {
        Statement query;
        try 
        {
            query = conn.createStatement();

            String sql = "SELECT data_x FROM table_x";
            ResultSet result = query.executeQuery(sql);

            result.next();
            int count = result.getInt("data_x");
            result.close();

            data_x_array = new String[count];

            for (int x = 1; x <= count; x++)
            {
                String data_x = result.getString(x);
                data_x_array[x] = data_x;
            }
        } 
        catch (SQLException e) 
        {
            e.printStackTrace();
        }
    }
    return data_x_array;
}

I just created a class, where data from the database is collected in an array.

Now i just want to return the array from this method.

But what i get is:

data_array cannot be resolved to a variable

Anybody could help me ?

Greetings!

UPDATE:

i changed snippet to:

public static String[] get_data()
{
    conn = getInstance();
    String[] data_array = null;
    if(conn != null)
    {
        Statement query;
        try 
        {
            query = conn.createStatement();

            String sql = "SELECT data_x FROM table_x";
            ResultSet result = query.executeQuery(sql);

            result.next();
            int count = result.getInt("data_x");
            result.close();

            data_array = new String[count];

            for (int x = 1; x <= count; x++)
            {
                String data_x = result.getString(x);
                data_x_array[x] = data_x;
            }
        } 
        catch (SQLException e) 
        {
            e.printStackTrace();
        }
    }
    return data_x_array;
}

When i compile just:

Invalid value for getInt() - 'value_in_table'

Anybody know this?

Greetings!

like image 776
user3683881 Avatar asked Oct 19 '14 16:10

user3683881


2 Answers

One more thing everyone forgot to mention

String[] data_array = new String[999];
for (int x = 0; x <= 999; x++){}

will throw an ArrayIndexOutOfBoundsException. Possible solution

String[] data_array = new String[999];
for (int x = 0; x < 999; x++){}
like image 176
SparkOn Avatar answered Sep 29 '22 11:09

SparkOn


You have defined your variable inside the while loop i.e. it is not visible to the return statement. Plus, you have defined your method as static void, meaning no return value is expected. Use static String [] instead.

like image 24
davek Avatar answered Sep 29 '22 11:09

davek