显示偶数和奇数的数量

时间:2015-02-02 09:42:25

标签: java

我们在编程中有一个任务,我们必须制作一个程序,其输出如下。给定值为(5,3,6,7,44,8,12,23,9,0),不应计算数字0。 任何人都可以告诉我,如果我的程序是正确的或需要更改,请帮助。

偶数:4 偶数是:6 44 8 12 奇数的数量:5 奇数是:5 3 7 23 9

    int array[] = {5,3,6,7,44,8,12,23,9,0};
    int evenNumbers[] = new int[array.length];
    int oddNumbers[] = new int[array.length];
    int even = 0;
    int odd = 0;

    //This will count the number of even except 0  
    for(int i = 0; i<10 ; i++){
        if(array[i] == 0)
            break;
        if(array[i]%2 == 0)
        even++;
        else
        odd++;             
    } 
    //This will put the even or odd numbers on their array
     for(int a = 0; a < array.length ; a++)
     {
       if(array[a]%2 == 0)
          evenNumbers[a] = array[a];

       else 
          oddNumbers[a] = array[a];

    }

    System.out.println("THE NUMBER OF EVEN NUMBERS ARE: "+even);
    System.out.print("THE EVEN NUMBERS ARE: ");

    //This will output the non zero values off evenNumbers[]
    for(int evenN = 0; evenN< array.length ; evenN++){

        if(evenNumbers[evenN]!= 0){
    System.out.print(" "+evenNumbers[evenN]);
        }       
   }     
    System.out.println("");

    System.out.println("THE NUMBER OF ODD NUMBERS ARE: "+odd);
    System.out.print("THE ODD NUMBERS ARE: ");
    for(int oddN = 0; oddN < array.length ; oddN++){

       //This will output the non zero values off oddNumbers[]
        if(oddNumbers[oddN]!= 0){
        System.out.print(" "+oddNumbers[oddN]);

        }
    }  

    }
}

1 个答案:

答案 0 :(得分:0)

你不应该在这里问这些问题。但是这对你有什么帮助,

您可以将其合并为1,而不是两个for循环,

for(int i = 0; i<10 ; i++){
    if(array[i] == 0)
        continue; //Skipping 0 but continue for Non-Zero
    if(array[i]%2 == 0)
    {
        evenNumbers[even] = array[i];//Copy Even number into even array
        even++;
    }
    else
    {
       oddNumbers[odd] = array[i];//Copy Odd number into Odd array
       odd++;             
    } 
}

//This will output the non zero values off evenNumbers[]
for(int evenN = 0; evenN< evenNumbers.length ; evenN++){
    //No need of this check here.//if(evenNumbers[evenN]!= 0)
    System.out.print(" "+evenNumbers[evenN]);     
}