从给定数字给出偶数,奇数和零

时间:2016-10-24 21:58:13

标签: java

我的comp sci课可以帮助我解决这个编程问题吗?我需要编写一个应用程序来读取用户给出的数字,然后打印奇数和偶数的数量以及零的数量。这就是我到目前为止所拥有的。当输入一个数字时,我会不断得到过多的偶数。

Scanner scan = new Scanner(System.in);

//3.6
int value;
int num = 0;
int even = 0;
int odd = 0;
int zero = 0;

System.out.println("Please enter a number.");
value = scan.nextInt();

while(value >= 0)
{
    num = (value % 10);

    if(num % 2 == 0)
    {

         even++;
    }
    else if(num % 2 != 0)
    {

        odd++;
    }
    else if(num == 0)
    {

         zero++;
    }

    value = value/10;
    System.out.println("even numbers: " + even);
    System.out.println("odd numbers: " + odd);
    System.out.println("zeros: " + zero);
}

3 个答案:

答案 0 :(得分:0)

只需将while(value >= 0)更改为while(value > 0)并重新排序if..else if语句,如下所示:

if(num == 0)
{
     zero++;
}
else if(num % 2 == 0)
{
     even++;
}
else if(num % 2 != 0)
{
    odd++;
}

通过这种方式,您也可以计算零。 (考虑0%2 == 0

答案 1 :(得分:0)

while(value >= 0){

        num = (value % 10);

        if(num == 0)
        {
            zero++;
             break;
        }
        else if(num % 2 != 0)
        {

            odd++;
        }
        else if(num % 2 == 0)
        {

             even++;
        }

        value = value/10;

    }
    System.out.println("even numbers: " + even);
    System.out.println("odd numbers: " + odd);
    System.out.println("zeros: " + zero);
   }

像这样编写代码可以提供如下输出:

Please enter a number.
512222

even numbers: 4
odd numbers: 2
zeros: 1

答案 2 :(得分:0)

以下是一个有效的简单解决方案:

    Scanner scan = new Scanner(System.in);

    //3.6
    int value;
    int num = 0;
    int even = 0;
    int odd = 0;
    int zero = 0;

    System.out.println("Please enter a number.");
    value = scan.nextInt();
    char[] charValue = String.valueOf(value).toCharArray();

    for (char c: charValue) {
        num = Character.getNumericValue(c);

        if (num == 0) {

            zero++;
        }else if (num % 2 == 0) {

            even++;
        } else {
            odd++;
        }
    }

    System.out.println("even numbers: " + even);
    System.out.println("odd numbers: " + odd);
    System.out.println("zeros: " + zero);