216k views
2 votes
Design and implement an application that determines and prints the number of odd, even, and zero digits in an integer value read from the keyboard.

1 Answer

5 votes

Answer:

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner scnr = new Scanner(System.in);

System.out.print("Enter a number to analyze: ");

int number = scnr.nextInt();

scnr.close();

int nrEven = 0;

int nrOdd = 0;

int nrZero = 0;

for (char digit : String.valueOf(number).toCharArray()) {

if (digit == '0')

nrZero++;

else if (digit % 2 == 1)

nrOdd++;

else

nrEven++;

}

System.out.printf("%d odd digits, %d even digits, %d zeros\\", nrOdd, nrEven, nrZero);

}

}

Step-by-step explanation:

An alternative way would be to do a switch statement on the digit.

User Abraham Brookes
by
4.0k points