Repetition of a Number Program in java

 


Question:

Pinky’s mom provides Pinky with a number and a key digit.  She wants Pinky to find out how many times that key digit appears in that number.  Help Pinky to do that by writing a program.

Sample Input 1:

Enter the number  16466

Enter the key digit   6

Sample Output 1:

6 appears 3 times in 16466

Sample Input 2:

Enter the number  8458

Enter the key digit   6

Sample Output 2:

6 appears 0 times in 8458

CODE:

import java.util.Scanner;


public class NumberRepetition
{
    public static void main (String[] args) {
        int num,key,times,r,flag=0;
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the number ");
        num=sc.nextInt();
        System.out.println("Enter the key digit ");
        key=sc.nextInt();
        int temp=num;
        while(temp>0)
        {
            r=temp%10;
            if(r==key)
            {
                flag++;
            }
            temp/=10;
        }
        System.out.println(key+" appears "+flag+" times in "+num);
    }
}
Previous
Next Post »