[英]copy specific row from one 2D array to another without system.arraycopy
因此,我必須編寫一個進入數組並從i行到j行並將這些行復制到新數組的方法。 這是我到目前為止提出的
public static void getRows(int i, int j, int[][] array){
int another[] = new int[j-i];
int n = 0;
for (int k = 0; k < array.length; k++){
while (i <= j){
if (k == i){
another[n] = array[k][0];
}
i++;
}
}
}
首先,您不會退貨或打印任何東西。 其次,要從輸入中復制多行,返回的數組應為2d(而不是1d)。 在j - i
行中創建一個new int[][]
。 然后從array
復制到新數組。 就像是,
public static int[][] getRows(int i, int j, int[][] array) {
int[][] ret = new int[j - i][];
for (int k = i; k < j; k++) {
ret[k - i] = new int[array[k].length];
for (int m = 0; m < ret[k - i].length; m++) {
ret[k - i][m] = array[k][m];
}
}
return ret;
}
然后,您可以使用類似的方法調用它(並打印結果)
public static void main(String[] args) {
int[][] t = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
System.out.println(Arrays.deepToString(getRows(1, 3, t)));
}
哪個輸出
[[2, 3], [4, 5]]
@艾略特我是這樣的:)
public static int[][] getRows(int i, int j, int[][] array){ int[][] another = new int[j-i+1][]; while (i <=j){ for (int k = 0; k < another.length; k++){ another[k]=array[i]; i++; } } return another; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.