Java: 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 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 :
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/java-exercises/method/java-method-exercise-17.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics