首页 > 解决方案 > 如何在 Java 的二维数组中将唯一值插入到下一个空索引?

问题描述

我想让二维数组的每个索引在每次迭代中都有一个唯一的值,但我的问题是,每当用户输入第一个索引的第一个值时,它会自动将剩余的空索引覆盖到第一个索引值中......

覆盖剩余空索引的结果

   String[][] ProductAllData1 = new String[10][6]; // an array that may store 10 unique elements(each element has 6 values)
   String[] receivedPInputs = getPInputs(); // gets the values from a function that asks the user to input values
 
   for (int d = 0; d < ProductAllData1.length; d++){      
         ProductAllData1[d] = receivedPInputs;
     
        System.out.print(Arrays.toString(ProductAllData1[d]));
        System.out.println("");
       
   }

我是否缺少要添加的内容或者我的 for 循环不正确?

您的回复将不胜感激!!

标签: javafor-loopmultidimensional-arrayindexing

解决方案


您正在为所有索引分配相同的值。

getPInputs()里面的循环!

String[][] ProductAllData1 = new String[10][6];
String[] receivedPInputs;
for (int d = 0; d < ProductAllData1.length; d++) {
    receivedPInputs = getPInputs();
    ProductAllData1[d] = receivedPInputs;

    System.out.print(Arrays.toString(ProductAllData1[d]));
    System.out.println("");
}

推荐阅读