7 Replies Latest reply: Jun 16, 2009 1:49 PM by jeisen

# Find the odd,even,zero digits of an integer

Hi,
Here i have an assignment I have to do. It is stated as a comment in the code. Every time I run the program, it thinks that every digit of the integer is odd because when I use String.indexOf on a number, it returns -1.
Can somebody help me edit this code?
Thanks
``````/*
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
*/

import java.util.Scanner;

public class OddEvenZero
{
public static void main (String[] args)
{
int odds = 0;
int evens = 0;
int zeros = 0;
Scanner scan = new Scanner (System.in);
System.out.println("Enter an Integer");
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)
zeros++;
else if
(numS.indexOf(i) % 2 == 0)
evens++;
else
odds++;
}

System.out.println("The number of odd digits = " + odds);
System.out.println("The number of even digits = " + evens);
System.out.println("The number of zero digits = " + zeros);
}
}``````
• ###### 1. Re: Find the odd,even,zero digits of an integer
The indexOf method returns a char. When you use a char in an logic statement like == or < or something it uses the chars ASCII value and not it's actual numerical value. Try converting it to an int.
• ###### 2. Re: Find the odd,even,zero digits of an integer
Ahh cr&alpha;p. Brain not working. I was thinking of charAt method. The indexOf method returns the index of that value in the String not the value itself.
• ###### 3. Re: Find the odd,even,zero digits of an integer
flounder wrote:
The indexOf method returns a char.
No, it returns an index. Me, I would stick with ints and avoid translating back and forth between int and string. Hint: you can get the last digit of num by using num % 10.
• ###### 4. Re: Find the odd,even,zero digits of an integer
@ the OP...

Use a switch statement or multiple if loops.
Each time a requirement is met then call a new method to do something in uniform.
• ###### 5. Re: Find the odd,even,zero digits of an integer
DrLaszloJamf wrote:
No, it returns an index.
Yeah, I corrected myself. I shouldn't try helping this early in the morning.
• ###### 6. Re: Find the odd,even,zero digits of an integer
I tried this and i copied and past it. but the even and zeros doesn't show when i run the program. help please
• ###### 7. Re: Find the odd,even,zero digits of an integer
I shouldn't have replied without checking why I didn't know this thread already. Please don't bring back old threads -- we'll be glad to help if you ask a question yourself. The code in this old thread wasn't working, why would you expect to be able to copy it?

Edited by: JEisen on Jun 16, 2009 2:48 PM