We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,263 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

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");
}
2
Contributors
1
Reply
1 Hour
Discussion Span
1 Year Ago
Last Updated
2
Views
marifergarz
Newbie Poster
1 post since Nov 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 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
302 posts since Oct 2010
Reputation Points: 43
Solved Threads: 28
Skill Endorsements: 0

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0682 seconds using 2.66MB