Java 程序统计正数组数

编写一个 Java 程序来计算正数组数并附带示例。或者如何编写一个 Java 程序来计算并返回给定数组中的正值或项。

在此 Java 正数组数示例中,我们使用 while 循环来迭代 count_PosArr 数组并计算正项(大于或等于零的数字)并打印它们。

package ArrayPrograms;

public class CountPositiveArrayItems0 {
	
	public static void main(String[] args) {
		
		int i = 0, count = 0;
		int[] count_PosArr = {-10, 15, -4, 11, -8, 22, 16, -11, 55, 18, -60};
		
		while(i < count_PosArr.length) 
		{
			if(count_PosArr[i] >= 0) {
				count++;
			}
			i++;
		}
		System.out.println("\nThe Total Number of Positive Items = " + count);
	}
}

使用 while 循环的数组中正数的计数输出

The Total Number of Positive Items = 6

使用 For 循环统计正数组数的 Java 程序

package ArrayPrograms;

import java.util.Scanner;

public class CountPositiveArrayItems1 {
	private static Scanner sc;
	
	public static void main(String[] args) {
		int Size, i, count = 0;
		
		sc = new Scanner(System.in);
		
		System.out.print("\nPlease Enter the CNT POS Array size  : ");
		Size = sc.nextInt();
		int[] count_PosArr = new int[Size];
		
		System.out.format("\nEnter CNT POS Array %d elements : ", Size);
		for(i = 0; i < Size; i++) 
		{
			count_PosArr[i] = sc.nextInt();
		}
	
		for(i = 0; i < Size; i++) 
		{
			if(count_PosArr[i] >= 0) {
				count++;
			}
		}
		System.out.println("\nThe Total Number of Positive Items = " + count);
	}
}
Java Program to Count Positive Array Numbers using for loop

在此正数组项 示例 中,我们创建了一个 CountPositiveElement 函数来计算正的 数组 项。

package ArrayPrograms;

import java.util.Scanner;

public class CountPositiveArrayItems2 {
	private static Scanner sc;
	
	public static void main(String[] args) {
		int Size, i;
		
		sc = new Scanner(System.in);
		
		System.out.print("\nPlease Enter the CNT POS Array size  : ");
		Size = sc.nextInt();
		int[] count_PosArr = new int[Size];
		
		System.out.format("\nEnter CNT POS Array %d elements : ", Size);
		for(i = 0; i < Size; i++) 
		{
			count_PosArr[i] = sc.nextInt();
		}
	
		int count = CountPositiveElement(count_PosArr, Size );
		
		System.out.println("\nThe Total Number of Positive Items = " + count);
	}
	
	public static int CountPositiveElement(int[] count_PosArr, int size ) {
		int i, count = 0;
		
		for(i = 0; i < size; i++) 
		{
			if(count_PosArr[i] >= 0) {
				count++;
			}
		}
		return count;
	}
}

使用 for 循环和函数统计数组中正项的输出。

Please Enter the CNT POS Array size  : 11

Enter CNT POS Array 11 elements : 2 4 -99 0 22 -33 11 -5 1 7 -9

The Total Number of Positive Items = 7