如何添加新的元素到下一个空索引在Java二维数组?



我有一个数组:

String[][] ProductAllData1 = new String[10][6]; //This array takes input 10 times

这个数组通常可以得到像{"John", "Mary", "Bonny", "Sadie", "Dutch", "Arthur"}

这样的输入我的问题是如何在数组的下一个空索引上插入另一个这样的输入?

我认为这可能需要一个递增索引,但我不确定如何在下一次迭代中使用for循环(就像每次迭代一样,一个新的输入将被插入到下一个空索引中。

正如您所说的,使用for循环并具有每次迭代递增的循环变量。使用这个变量作为数组的索引。

for(int i=0;i<size;i++){
String[] input = null; // replace this null with the input
array[i] = input;
}

你可以使用一个类似的循环和不同的循环变量来获取input数组

的元素

该数组定义为一个String[][],有10行,每行有6个元素。

提供的第一行有六个名称。

如果数组必须包含另外9个元素,则需要一种方法来增加第一个索引。最简单的方法是使用变量。

String[][] arr = new String[10][6];
boolean moreInput = true;
for (int i = 0; i < 10 && moreInput; i++) {
arr[i] = ... ; // get the input you need for index i
moreInput = ... ; // ask the user or whatever process it is that is populating the array if there is more input to read into the array
}

您需要遍历外部数组,并使用一个空的内部数组查找下一个元素。您可以通过测试外部元素是指向null还是指向一个没有元素的数组来实现这一点。

for (int i = 0; i < ProductAllData1.length; i++) {
if (ProductAllData1[i] == null || ProductAllData1[i].length == 0) {
ProductAllData[i] = inputArray;
}
}
  • ProductAllData1[i] == null->外部元素不指向任何
  • ProductAllData1[i].length == 0->外部元素指向一个没有元素的内部数组

相关内容

最新更新