w3resource

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:

Java Method Exercises: In an integer, count the number of digits with value 2

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 :

Flowchart: In an integer, count the number of digits with value 2

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.



Share this Tutorial / Exercise on : Facebook and Twitter

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