I was coding midway when I find out that netbeans give me an error regarding the below code:
String [][]table={getRowArray()};
//getRowArray() will return me a 1D string array
Is there any way to store the 1D array returned by my method into the 2D array directly instead of using a for loop? Thanks for any help rendered!
For starters - yes, it is possible to do that.
public class Test {
public String[] dum() {
String[] x = {"Not sure"};
return x;
}
public static void main(String[] args) {
Test t = new Test();
String[][] words = {t.dum()};
System.out.println(words[0][0]); // prints "Not sure"
}
}
Double check the error you're getting. Make certain that the return type of getRowArray()
is truly String[]
.
There may be a better solution for this, but I believe you need to specify a single index for one of the dimensions in order to store it, so you're storing the 1-d Array into a single index of the first-dimension.
ie
String [][]table;
table[0] = getRowArray();
this should work since the first dimension of the array stores other arrays
String [] oneD = { "1", "2", "3", "4" }; // getRowArray();
String [][] twoD1 = { oneD };
String [] anotherOneD = null; // or filled
String [][] twoD2 = { oneD, anotherOneD };
String [][] twoD3 = new String[][] { oneD };
String [][] twoD4 = new String[][] { oneD, anotherOneD };
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.