编写一个 Java 程序,使用 for 循环计算数组中元素的出现次数。此程序接受数组的大小、数组元素以及要搜索的项目。
for 循环会遍历数组中的每个元素,if 语句会将该元素与数字进行比较。如果两者都匹配,则出现次数变量会加一。最后,我们将出现次数变量作为输出打印出来。
package NumPrograms;
import java.util.Scanner;
public class ArrayCountOccrence1 {
private static Scanner sc;
public static void main(String[] args) {
int Size, i, num, occr = 0;
sc = new Scanner(System.in);
System.out.print("Please Enter the Array size = ");
Size = sc.nextInt();
int[] arr = new int[Size];
System.out.format("Enter the Array %d elements : ", Size);
for(i = 0; i < Size; i++)
{
arr[i] = sc.nextInt();
}
System.out.print("Please Enter the Array Item to Know = ");
num = sc.nextInt();
for(i = 0; i < arr.length; i++)
{
if(arr[i] == num)
{
occr++;
}
}
System.out.println(num + " Occurred " + occr + " Times.");
}
}

此 Java 程序使用 while 循环计算数组中元素的出现次数。
package NumPrograms;
import java.util.Scanner;
public class ArrayCountOccrence2 {
private static Scanner sc;
public static void main(String[] args) {
int Size, i, num, occr = 0;
sc = new Scanner(System.in);
System.out.print("Please Enter the size = ");
Size = sc.nextInt();
int[] arr = new int[Size];
System.out.format("Enter the %d elements : ", Size);
i = 0;
while( i < Size)
{
arr[i] = sc.nextInt();
i++;
}
System.out.print("Please Enter the Array Item to Know = ");
num = sc.nextInt();
i = 0;
while( i < arr.length)
{
if(arr[i] == num)
{
occr++;
}
i++;
}
System.out.println(num + " Occurred " + occr + " Times.");
}
}
Please Enter the size = 7
Enter the 7 elements : 22 9 22 7 54 22 1
Please Enter the Array Item to Know = 22
22 Occurred 3 Times.
此 示例 使用 do while 循环来计算给定数组中元素的出现次数。
package NumPrograms;
import java.util.Scanner;
public class ArrayCountOccrence3 {
private static Scanner sc;
public static void main(String[] args) {
int Size, i, num, occr = 0;
sc = new Scanner(System.in);
System.out.print("Please Enter the Item to Know = ");
num = sc.nextInt();
System.out.print("Please Enter the size = ");
Size = sc.nextInt();
int[] arr = new int[Size];
System.out.format("Enter the %d elements : ", Size);
i = 0;
do
{
arr[i] = sc.nextInt();
if(arr[i] == num)
{
occr++;
}
} while(++i < Size);
System.out.println(num + " Occurred " + occr + " Times.");
}
}
Please Enter the Item to Know = 5
Please Enter the size = 9
Enter the 9 elements : 5 2 5 9 11 5 22 7 5
5 Occurred 4 Times.