java数组之foreach遍历数组之正负数数量统计 
时间: 2023-04-28 21:01:11 浏览: 45
可以使用foreach遍历数组,统计其中正数和负数的数量。
具体实现方法如下:
1. 定义一个整型数组,用于存储需要统计的数据。
2. 使用foreach循环遍历数组,对于每个元素,判断其正负性,并分别累加计数器。
3. 输出统计结果,即正数和负数的数量。
示例代码如下:
int[] nums = {1, -2, 3, -4, 5, -6, 7, -8, 9, -10};
int positiveCount = ;
int negativeCount = ;
for (int num : nums) {
if (num > ) {
positiveCount++;
} else if (num < ) {
negativeCount++;
}
}
System.out.println("正数数量:" + positiveCount);
System.out.println("负数数量:" + negativeCount);
相关问题
使用java完成:数组操作之遍历
可以使用 for 循环或者 foreach 循环遍历数组,示例代码如下:
```java
public class ArrayTraversal {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
// 使用 for 循环遍历数组
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
// 使用 foreach 循环遍历数组
for (int num : arr) {
System.out.print(num + " ");
}
}
}
```
该代码演示了使用 for 循环和 foreach 循环遍历数组的方法。
Java数组有几种遍历方法
Java数组有以下几种遍历方法:
1. for循环遍历:使用for循环遍历数组,通过数组的下标访问数组元素。
2. 增强for循环遍历:使用增强for循环(foreach)遍历数组,可以遍历数组的所有元素,不需要使用数组下标。
3. 迭代器遍历:使用迭代器(Iterator)遍历数组,可以遍历数组的所有元素,不需要使用数组下标。
4. Lambda表达式遍历:使用Lambda表达式遍历数组,可以遍历数组的所有元素,不需要使用数组下标。
5. Stream流遍历:使用Stream流遍历数组,可以遍历数组的所有元素,不需要使用数组下标。
相关推荐








