简体   繁体   中英

how can I count the number of odd, evens, and zeros in a multiple digit number in Java

My program does not count 0 as an even number And I don't want to use for statement just while loop thank you

import java.util.*;

public class DigitAnalyst {

public static void main(String[] args) {
    int  zero=0;
    int lastdigit;

    Scanner inputNumber= new Scanner(System.in);
    System.out.println("enter any number: ");
    int number = inputNumber.nextInt();

    while(number > 0)
    {

         int zeros=0;
         int odds=0;
         int evens=0;

               while(number > 0)

                        {
                                 number=number/10;
                                 lastdigit=number%10;



                                 if (lastdigit==zero)
                                     zeros++;
                                 if (lastdigit % 2 == zero)
                                     evens++;
                                 if (lastdigit % 2 != zero)
                                     odds++;
                        }

               System.out.println(odds +" odd digits");
               System.out.println(evens +" even digits");
               System.out.println(zeros +" zero digits");
       }

}

}

Based on your code, it does count 0 as an even number, since 0 % 10 == 0 .

Yet I think your problem comes from number=number/10; which is executed when entering the loop.

Try instead to put this statement at the end of the loop:

while (number > 0) {
    lastdigit = number % 10;
    // increment counters
    number = number / 10;
}

I'm not entirely clear on what the problem is, but I suspect that you simply need to reorganize your logic a bit with else . Instead of this:

if (lastdigit==zero)
    zeros++;
if (lastdigit % 2 == zero)
    evens++;
if (lastdigit % 2 != zero)
    odds++;

use this:

if (lastdigit==zero)
    zeros++;
else if (lastdigit % 2 == zero)
    evens++;
else
    odds++;

That way, if lastdigit is zero , it won't count as either even or odd (which I'm guessing is the behavior you want).

All you need to do is instead of the three if statements, format them as this:

   if (lastdigit % 2 != zero){
       odds++;
   }
   if (lastdigit==zero) {
       zeros++;
   } else if (lastdigit % 2 == zero) {
       evens++;
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM