Monday 28 May 2018

Find sum of all even digits in String




Sample Program:-


public class SumOfAllEven {  
      public static void main(String[] args) {  
           String s = "1j2a3v4a0";  
     char ch[] = s.toCharArray();  
     int sum = 0;  
     for (int i = 0; i < ch.length; i++) {  
         try {  
            int x = Integer.valueOf(String.valueOf(ch[i]));  
            if (x % 2 == 0) {  
               sum += x;  
            }  
         } catch (Exception e) {  
         }  
     }  
     System.out.println(sum);  
      }  
 }  



Output:-


 6  


Explanation:-

Suppose we have String s="java232";
Output for this will be 2+2=4

Enjoy Coding.

No comments:

Post a Comment