954,523 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Count of odd digits in a number

I need help with a lab I'm doing. In this lab you have to show the number of odd digits a number has, for example the number 4135 would have three odd digits. I've already done a lab where it tells you if a number is odd or even but I don't know how to change it and make it to do what it needs to.

This is my code for the odd or even lab:

/**
* It reads and number and determines if that number is even or add.
*/

import java.util.Scanner;
public class Odd_or_Even
{
public static void main(String [] args)
{
Scanner reader = new Scanner (System.in);
int answer;
System.out.print("Enter 1 to enter a number or 2 to quit -> ");
answer = reader.nextInt();

while (answer == 1)
{calculate();
System.out.print("Want to enter another number? Enter 1 for yes or 2 to quit -> ");
answer = reader.nextInt();
}

if (answer == 2)
System.out.println("Thanks for using this program");

else {
System.out.println("Error this number ("+answer+") is not an option try again.");

}
}

public static void calculate()
{
Scanner reader = new Scanner (System.in);
int num;
int finalresult;

System.out.print("Enter your number -> ");
num = reader.nextInt();

finalresult = num%2;

if (finalresult == 0)
System.out.println("Your number ("+num+") is an even number");
else
System.out.println("Your number("+num+") is and odd number");
}

marifergarz
Newbie Poster
1 post since Nov 2011
Reputation Points: 10
Solved Threads: 0
 

You have to read the number and find a way to extract individual digits from the number.

You can do this in two ways:

1. Read the number into a string. And use String ops to extract each number and parse it to integer and test for odd or even on each number

2. Read the number as an integer and do some math to extract each digit.
[hint: 4505 % 10 = 5 and 4505 / 10 = 450]

stevanity
Posting Whiz in Training
293 posts since Oct 2010
Reputation Points: 43
Solved Threads: 28
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: