JAVA:我想在数组中打印偶数和奇数的数字

时间:2015-11-06 15:50:18

标签: java arrays

这是我的代码:

    int[] p = {1,2,3,4,5};

    System.out.print("Even numbers: ");
    for (int i = 0; i < p.length; i++) {

        if (p[i] == 0) {
        } else if (p[i] % 2 == 0) {
            System.out.print(p[i] + " ");
        }

    }

    System.out.print("\nOdd numbers: ");
    for (int i = 0; i < p.length; i++) {
        if (p[i] % 2 != 0) {
            System.out.print(p[i] + " ");
        }
    }

此程序打印:

Even numbers: 2 4
Odd numbers: 1 3 5

接下来我想改变我的代码来打印这样的东西:

Even numbers: 2
Odd numbers: 3

这意味着我想在数组中打印偶数和奇数intigers的数量。

我该怎么做?

2 个答案:

答案 0 :(得分:1)

只需保留一个计数器

int[] p = {1,2,3,4,5};
int oddCount=0;
int evenCount=0;

    System.out.print("Even numbers: ");
    for (int i = 0; i < p.length; i++) {

        if (p[i] == 0) {
        } else if (p[i] % 2 == 0) {
            System.out.print(p[i] + " ");
            evenCount++;
        }

    }

    System.out.println("Evencount"+evenCount);

    System.out.print("\nOdd numbers: ");
    for (int i = 0; i < p.length; i++) {
        if (p[i] % 2 != 0) {
            System.out.print(p[i] + " ");
            oddCount++;
        }
    }

    System.out.println("Odd count"+oddCount);

答案 1 :(得分:0)

class Test
{
    public static void main(String args[])
    {
    int noEven=0;
    int noOdd=0;
    int[] p = {1,2,3,4,5};
    System.out.print("Even numbers: ");
    for (int i = 0; i < p.length; i++) {

        if (p[i] == 0) {
        } else if (p[i] % 2 == 0) {
            //System.out.print(p[i] + " ");
            noEven++;
        }

    }
    System.out.println(noEven);

    System.out.print("\nOdd numbers: ");
    for (int i = 0; i < p.length; i++) {
        if (p[i] % 2 != 0) {
            //System.out.print(p[i] + " ");
            noOdd++;
        }
    }
    System.out.println(noOdd);
}
}