编写一个 Java 程序,通过示例查找数组中的元素数量。例如,我们可以使用数组的 length 属性来查找并打印元素的总数。
package NumPrograms;
public class ArrayCountElements1 {
public static void main(String[] args) {
int[] arr = new int[] {10, 20, 30, 40, 50, 60};
int count = arr.length;
System.out.println("The Total Number of Elemenst in an Array = " + count);
}
}

此程序使用 for 循环查找数组中的元素数量。
package NumPrograms;
public class Example2 {
public static void main(String[] args) {
int[] arr = new int[] {22, 99, 8, 17, 6, 11, 1, 15, 2, 5, 4};
int count = 0;
for(int i : arr)
{
count++;
}
System.out.println("The Total Number = " + count);
}
}
The Total Number = 11
在此 示例 中,我们使用了 while 循环来迭代数组项,并添加了条件来检查元素是否等于字符 x。
package NumPrograms;
public class Example3 {
public static void main(String[] args) {
int[] arr = new int[] {1, 9, 11, 4, 7, 22, 9, 17, 8};
int count = 0;
int i = 0;
try
{
while(arr[i] != 'x')
{
count++;
i++;
}
}
catch(Exception e)
{
System.out.println("The Total Number of Items = " + count);
}
}
}
The Total Number of Items = 9