Java Programming | Counting Occurrence of digit in number

Introduction

This is a tutorial for counting occurrence of digit in number. The program is given below that counts the occurrence of given digit in given number. The program is not extendable. Go enjoy the program. Lets begin…….

Program for counting occurrence of digit in number.

//import Scanner as we require it.
import java.util.Scanner;

// the name of our class its public
public class Occurence {
	//void main
		public static void main (String[] args)
		{
			//declare int
			int no,oc=0,digit,m;

			//Declare input as scanner
			Scanner input = new Scanner(System.in);

			//Take input
			 System.out.println("Enter Number :");
			 no = input.nextInt();
			 System.out.println("Enter digit :");
			 digit = input.nextInt();

			//add while loop
			while(no>0)
			{
				m=no%10;
				if(m==digit)
					oc++;
				no=no/10;
			}

			System.out.println("Digit occurred "+oc+" times");
		}
}

Output

Enter Number :
12223
Enter digit :
2
Digit occurred 3 times

How does it work

  1. You enter the number.
  2. You enter the digit
  3. In while loop last digit is separated and matched with given digit.
  4. If matched true, then increases the oc by one value.
  5. Prints the occurrence.

Extending it

The program cannot be extended.

Explanation.

  1. Import the Scanner.
  2. Declare the class as public
  3. Add the void main function
  4. Add system.out.println() function with the message to enter number and digit.
  5. Declare input as Scanner.
  6. Take the inputs and save it in variables.
  7. Add a loop and count the occurrence.
  8. Add system.out.println() function to print the occurrence.

At the end.

You learnt creating the Java program for Counting occurrence of digit in number. So now enjoy the program.

Please comment on the post and share it.
And like it if you liked.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s