JayLo
JayLo

Reputation: 63

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");
       }

}

}

Upvotes: 0

Views: 1205

Answers (3)

Jean Logeart
Jean Logeart

Reputation: 53819

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;
}

Upvotes: 1

PsyCode
PsyCode

Reputation: 664

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++;
   }

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234795

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).

Upvotes: 0

Related Questions