1

Whats the nicest way to fill up following array:
From main:

String[][] data = new String[x][3]; 

for(int a = 0; a < x; a++){ 
    data[a] = someFunction();
}

Function I am using..:

 public String[] someFunction(){
     String[] out = new String[3];

     return out;
 }

Is it possible to do something like this? Or do I have to fill it with for-loop?

With this code im getting error "non-static method someFunction() cannot be refferenced from static content ---"(netbeans) on line data[a] = someFunction();

1
  • You could try this out, perhaps? Not sure how you want to produce the data for the array elements... Commented Jan 8, 2015 at 12:01

2 Answers 2

1

You have to specify how many rows your array contains.

String[][] data = new String[n][];

for(int i = 0; i < data.length; i++){
    data[i] = someFunction();
}

Note that someFunction can return arrays of varying lengths.

Of course, your someFunction returns an array of null references, so you still have to initialize the Strings of that array in some loop.

I just noticed the error you got. Change your someFunction to be static.

Sign up to request clarification or add additional context in comments.

5 Comments

I did specify. String[][] data = new String[x][3]; x*3 and someFunction gives String[] out = new String[3];
@Vedran My mistake. I thought you meant that x implies an arbitrary length.
Any idea what I could do?
@Vedran change your someFunction method to static.
oh. totally missed that. Thanks for your help!
0

Change your someFunction() by adding "static".

You also should consider using an ArrayList for such tasks, those are dynamic and desinged for your purpose (I guess).

public static void main(String[] args){

    int x = 3;

    String[][] data = new String[x][3]; 

    for(int a = 0; a < x; a++){ 
        data[a] = someFunction();
    }

}

public static String[] someFunction(){
     String[] out = new String[3];
     return out;
 }

Greetings Tim

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.