Imani M. Jackson
Imani M. Jackson

Reputation: 201

Conditionals and Loops exercise

Im stuck with an exercise Im doing it says "Write a program that determines and prints the number of odd,even, and zero digits in an integer value read from the keyboard.What am I doing wrong and how can I correct my mistakes?

import java.util.Scanner;

public class OddEven {
   public static void main(String[] args){
   Scanner scan = new Scanner(System.in);

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

   System.out.println("Enter a value: ");
   value=scan.nextInt();
   if (value%2==0)
       even=even+1;
   else
       odd=odd+1;
   System.out.println("even = "+ even);
   System.out.println("odd = "+odd);
   System.out.println("zero = "+zero);
   }
}

Upvotes: 1

Views: 108

Answers (2)

Seelenvirtuose
Seelenvirtuose

Reputation: 20608

The conditional statement

if (value%2==0)
    even=even+1;
else
    odd=odd+1;

does not count the odd or even digits. It simply determines whether the entered value (the whole value) is odd or even.

As this is obviously a homework question, I will only give some hints:

  1. You have to loop through all digits. In a decimal system there is an easy integer way to both get the last digit and the remaining digits as a new but smaller integer value.
  2. Once you have the single (last) digit, you can check it for being odd, even, or zero.
  3. The loop ends when the remaining value from step 1 gets 0. Some caution: There must be a special check at the beginning because the original value could have been already 0.

Look at the other answers that already provide you some code. But as a beginner you really should first try to write that code yourself.

Upvotes: 1

Maljam
Maljam

Reputation: 6274

You have to check for each digit at a time:

int odd, even, zero, value;
value = scan.nextInt();

while(value > 0) {
    int digit = value%10; //isolates only the last digit
    if(digit==0)zero++;
    else if(digit%2==0)even++;
    else odd++;
    value /= 10; //removes the last digit
}

Upvotes: 1

Related Questions