Reputation: 201
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
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:
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
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