Java: In an integer, count the number of digits with value 2
Count Occurrences of Digit '2' in Integer
Write a Java method to count the number of digits in an integer with the value 2. The integer may be assumed to be non-negative.
Pictorial Presentation:

Sample:
Input: 12541
Output: 1
Input: 25672
Output: 2
Input: 9484
Output: 0
Sample Solution:
Java Code:
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Input a number: ");
int n = in.nextInt();
if (n>0)
{
System.out.println(test(n));
}
}
public static int test(int num)
{
int ctr = 0;
int n = num;
do{
if (n % 10 == 2){
ctr ++;
}
n /= 10;
}while(n > 0);
return ctr;
}
}
Sample Output:
Input a number: 12541 1
Flowchart :
For more Practice: Solve these Related Problems:
- Write a Java program to count the occurrences of a specified digit in an integer.
- Write a Java program to count the number of times the digit '2' appears in a range of integers.
- Write a Java program to count occurrences of digit '2' in an integer using a recursive approach.
- Write a Java program to count the occurrences of the digit '2' in the binary representation of an integer.
Java Code Editor:
Contribute your code and comments through Disqus.
Previous Java Exercise: Find all twin prime numbers less than 100.
Next Java Exercise: Three integers and check whether they are consecutive
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics