我在将字符串数组的内容传递到另一个数组并获取数组的长度时遇到问题。
以下是我的详细问题:
我创建了一个名为 DRO 的字符串数组,其中包含两个内容
String[] DRO = {"DRO1", "DRO2"};
DRO 中的每个数组元素也有其数组
int[] DRO1 = {3,4,9,10, 11}; int[] DRO2 = {10,5,8,2};
创建一个循环来遍历组“DRO”。 在 group_name.length 我被困住了。 我无法让“DRO1”传入并读取“DRO1.length”。 相反,它显示我使用“DRO1.length();”。 例如,如果我使用“length() 而不是 .length”,它将返回“DRO1”的字符串长度 (4),而不是 DRO1 的数组编号 (5)。
我想要实现的目标是传入“group_name.length”->“DRO1.length”并获取 DRO1 的数组长度为 5,以便通过另一个循环我可以对 DRO1 数组的内容求平均值,然后进行至 DRO2
这是我得到的,感谢您的帮助
for (int x=0; x< DRO.length; x++) // loop DRO groups
{
String group_name = DRO[x];
for (int i=0; i< group_name.length; i++) // <== here is where I don't know how to get array DRO1 length.
{
System.out.printf("[Site %d] %-15s - %s%n", site,"DRO", i);
System.out.printf("value= %s\n", capData[i]);
group_name_AVE= (group_name+ capData[i]);
int array_num = group_name.length;
if (i == array_num-1) {
group_name_AVE= (group_name_AVE/group_name.length)/12;
System.out.printf("[Site %d] %-15s - %s%n", site,"group_name_AVE", group_name_AVE, "Mhz");
}
}
}
执行此任务的一种方法是使用 int[][] 二维数组,例如:
// Two Dimensional Array - an int[][] array of int[] arrays:
int[][] dro = {
{3, 4, 9, 10, 11}, // First int[] array at Row index 0;
{10, 5, 8, 2} // Second int[] array at Row index 1;
};
// StringBuilder - Used to build the current int[] array string:
StringBuilder sb = new StringBuilder("");
// An int variable to hold the total sum of elemental values
// in the current int[] array:
int arraySum;
// Iterate through each int[][] array row (outer loop):
for (int x = 0; x < dro.length; x++) {
arraySum = 0; // Zero the summing variable to prep for new int[] array:
// Iterate through each column of the current inner int[] array (inner loop):
for (int i = 0; i < dro[x].length; i++) {
// Retrieve the current element value:
int arrayElementValue = dro[x][i];
// If sb is not empty then append a comma/space to the string build:
if (!sb.toString().isEmpty()) {
sb.append(", ");
}
// Append the current array element value to the string build:
sb.append(arrayElementValue);
// Sum the current element value to the overall total:
arraySum += arrayElementValue;
// Continue processing current array columns until inner loop is done...
}
// Display information about the currently processed inner array:
System.out.printf("Site #%d - %-15s%n", x+1, "DRO" + (x+1) + ": [" + sb.toString() + "]");
System.out.println("The array (DRO" + (x+1) + ") contains " + dro[x].length + " integer elements");
System.out.println("with an average numerical value of: " + (arraySum / dro[x].length) + "Mhz." );
System.out.println();
// Empty the current string build in preparation for a New string build:
sb.setLength(0);
// Continue outer loop until done...
}
// DONE
Site #1 - DRO1: [3, 4, 9, 10, 11]
The array (DRO1) contains 5 integer elements
with an average numerical value of: 7Mhz.
Site #2 - DRO2: [10, 5, 8, 2]
The array (DRO2) contains 4 integer elements
with an average numerical value of: 6Mhz.