编写一个 Java 程序来打印负数数组,并附带示例。或如何编写一个 Java 程序来查找并返回给定数组中的负数项。在此负数数组计数示例中,我们使用 `while` 循环来迭代 `count_NegArr` 数组并计算负数项(小于零的数字),然后打印它们。
package ArrayPrograms;
public class NegativeArrayItems {
public static void main(String[] args) {
int j = 0;
int[] Neg_arr = {-40, 15, -4, 11, -8, -13, 22, 16, -11, -99, 55, 18, -60};
System.out.print("\nList of Negative Numbers in NEG Array : ");
while(j < Neg_arr.length)
{
if(Neg_arr[j] < 0) {
System.out.format("%d ", Neg_arr[j]);
}
j++;
}
}
}
使用 `while` 循环输出的负数数组
List of Negative Numbers in NEG Array : -40 -4 -8 -13 -11 -99 -60
使用 For 循环打印负数数组的 Java 程序
此 Java 负数数组项示例允许用户输入 `Neg_arr` 数组的大小和项。
package ArrayPrograms;
import java.util.Scanner;
public class NegativeArrayItems1 {
private static Scanner sc;
public static void main(String[] args) {
int Size, i;
sc = new Scanner(System.in);
System.out.print("\nPlease Enter the NEG Array size : ");
Size = sc.nextInt();
int[] Neg_arr = new int[Size];
System.out.format("\nEnter NEG Array %d elements : ", Size);
for(i = 0; i < Size; i++)
{
Neg_arr[i] = sc.nextInt();
}
System.out.print("\nList of Negative Numbers in NEG Array : ");
for(i = 0; i < Size; i++)
{
if(Neg_arr[i] < 0) {
System.out.format("%d ", Neg_arr[i]);
}
}
}
}

在此负数数组项 示例 中,我们创建了一个单独的函数 `NegativeElement` 来打印给定 数组 中的负数数组项。
package ArrayPrograms;
import java.util.Scanner;
public class NegativeArrayItems2 {
private static Scanner sc;
public static void main(String[] args) {
int Size, i;
sc = new Scanner(System.in);
System.out.print("\nPlease Enter the NEG Array size : ");
Size = sc.nextInt();
int[] Neg_arr = new int[Size];
System.out.format("\nEnter NEG Array %d elements : ", Size);
for(i = 0; i < Size; i++)
{
Neg_arr[i] = sc.nextInt();
}
NegativeElement(Neg_arr, Size);
}
public static void NegativeElement(int[] Neg_arr, int size ) {
int i;
System.out.print("\nList of Negative Numbers in NEG Array : ");
for(i = 0; i < size; i++)
{
if(Neg_arr[i] < 0) {
System.out.format("%d ", Neg_arr[i]);
}
}
}
}
使用 For 循环和函数输出的负数数组项。
Please Enter the NEG Array size : 9
Enter NEG Array 9 elements : -1 5 0 11 -2 -3 99 3 -5
List of Negative Numbers in NEG Array : -1 -2 -3 -5