Java Method Exercises: In an integer, count the number of digits with value 2
Java Method: Exercise-17 with Solution
Write a Java method to count the number of digits in an integer that have 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 :
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.
Java: Tips of the Day
Prefer primitive classes
Wrapper classes are often slower than primitive classes. While Primitive class only has values, the wrapper class stores information about the entire class. Since the classes often deal with object values, comparing them with primitive classes does not give the desired results.
Ref: https://bit.ly/3eItLCN
- Exercises: Weekly Top 12 Most Popular Topics
- Pandas DataFrame: Exercises, Practice, Solution
- Conversion Tools
- JavaScript: HTML Form Validation
- SQL Exercises, Practice, Solution - SUBQUERIES
- C Programming Exercises, Practice, Solution : For Loop
- Python Exercises, Practice, Solution
- Python Data Type: List - Exercises, Practice, Solution
- C++ Basic: Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - exercises on Employee Database
- SQL Exercises, Practice, Solution - exercises on Movie Database
- SQL Exercises, Practice, Solution - exercises on Soccer Database
- C Programming Exercises, Practice, Solution : Recursion