Java 程序:计算数组中元素个数

原文:https://www.studytonight.com/java-programs/java-program-to-find-the-number-of-elements-in-an-array

在本教程中,我们将学习如何查找数组中存在的元素总数。但是在继续之前,如果您不熟悉数组的概念,那么请务必查看 Java 中的文章数组

输入:数组元素为:9 8 7 0 6 5 4 3 4 5 2 1

输出:数组中的元素总数为 13

程序 1:计算数组中元素的数量

在这个方法中,我们将看到如何使用每个循环的来计算数组中存在的元素数量。

算法

  1. 开始
  2. 声明一个数组。
  3. 初始化数组。
  4. 声明一个变量计数来存储数组中的元素数量。
  5. 将其初始化为 0。
  6. 对每个循环使用,以迭代数组中的所有元素。
  7. 在每次迭代中增加计数变量。
  8. 打印数组中元素的总数。
  9. 现在,打印数组元素。
  10. 停下来。

下面的程序演示了如何为每个循环使用计算数组中元素的总数。首先,我们声明一个数组,然后对每个循环使用一个来确定数组中存在的元素总数。

/*Java Program to find the number of elements present in an array*/

import java.util.*;  
import java.util.Arrays; 

//Driver Code
public class Main  
{  
   public static void main(String args[])   
   {  
        int a[] = {9,8 ,7 ,0 ,6 ,5 ,4 ,7 ,3 ,4 ,5 ,2 ,1};   //Declare and Initialize an array
        int count=0;           //Declare variable to count the number of elements in an array and initialize it to 0

        //Use a for each loop to iterate through all the elements in an array
        //Print the elements present in the array
        System.out.println("The entered elements are: ");
        for(int i:a)
        {
             System.out.print(a[i]+" ");
            count++;    //Increment the count variable
        }
        System.out.println("");
        //Print the total number of elements present
        System.out.println("The total number of elements in an array is "+count);

   }
}

输入的元素是: 4 3 7 9 4 5 6 7 0 6 5 7 8 数组中的元素总数是 13

程序 2:计算数组中元素的数量

在这个方法中,我们将看到如何使用内置函数计算数组中存在的元素数量。Java 提供了一个内置函数length(),返回数组的总长度。数组的总长度只不过是数组中元素的总数。

算法

  1. 开始
  2. 声明一个数组。
  3. 初始化数组。
  4. 声明一个变量计数来存储数组中的元素数量。
  5. 使用内置函数计算数组的长度。
  6. 打印数组的长度。
  7. 使用 for 循环遍历所有元素。
  8. 打印所有数组元素。
  9. 停下来。

下面是相同的代码。

下面的程序演示了如何使用 try-catch 块计算数组中的元素总数。首先,我们声明并初始化数组,然后使用内置函数来确定数组中存在的元素总数。

/*Java Program to find the number of elements present in an Array using in-built functions*/

public class Main
{
    //Driver Code
    public static void main(String[] arr)
    {
        int a[] = {91,28 ,47 ,30 ,56 ,65 ,74 ,87 ,93 ,24 ,15 ,82 };   //Declare and Initialize an array

        //Declare a variable to store the length of the array

        int count=a.length; //Use an in-built function to calculate the length of an array

        System.out.println("The number of elements in the array are : "+count); //Print the length of the array

        //Print the array elements
        System.out.println("The Array Elements are ");

        for(int j=0;j<count;j++)
        {
            System.out.print(a[j]+" ");
        }
        System.out.println("");
    }
}

数组中的元素个数为:12 数组元素为 91 28 47 30 56 65 74 87 93 24 15 82