I need to design an application that determines and prints the number of odd, even, and zero digits in an integer value read from the keyboard. This is what I have so far.

public static void main (String[] args)
        int odd=0, even=0, zero=0;

        Scanner scan = new Scanner(System.in);
        int num = scan.nextInt();

        String numS = Integer.toString(num);
        int digits = numS.length();

        for (int i = 0; i < digits; i++)
            if (numS.indexOf(i) == 0)
            else if (numS.indexOf(i) % 2 == 0)

        System.out.println("The number of odd digits are: " + odd);
        System.out.println("The number of even digits are: " + even);
        System.out.println("The number of zero digits are: " + zero);

Recommended Answers

All 3 Replies

What's your question? One thing I see right off the bat is you're not converting the characters from the string to integers before checking if they're zero, odd, or even. The Integer class might help a bit (specifically parseInt()). Also, indexOf() looks up the index of the specified character in the string. Read about the methods provided by the String class and you shouldn't have any problem (look into charAt(), which may change how you use parseInt(), if you do at all).

You are on the right track. You attempt to check for digit number using indexOf() method which is wrong.

In your loop, get rid of indexOf() method but use charAt(i) instead. The returned value of the charAt() method is a char which could directly be compared (using == symbol) with another char with single quotation ('). For example, '0' is a char of letter zero digit number.

charAt() can be casted to int for checking odd/even digit as well. However, remember that the casted integer value is the ASCII value of the letter, not the number it appears.

String a = "123450";
// ASCII values start from 48 which is 0, 49 which is 1, and so on...
int ch = (int) a.charAt(2);  // integer is 50, not 2
int digitValue = ch - 48;    // now the number is really 2

You could use Integer.parseInt() but you will need to extract each digit using either substring() method from String class or Character.toString() from Character class because the parseInt() takes a string, not character. It will be a different approach from what you are doing.

int digitValue = ch - 48;    // now the number is really 2

Poorly documented code. Who knows what 48 is.
Better would be:

int digitValue = ch - '0';    // now the number is really 3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.