program to Find sum of all even digits in string in java


In this core java programming tutorial we will write a program to Find sum of all even digits in string in java.


Example 1 in java>
Input > java grey243
Output > 6


Example 2 in java>
Input > java64 is12
Output > 12

Program/ example to Find sum of all even digits in string in java >
public class FindSumOfAllEvenDigitInString {
   public static void main(String[] args) {
          String s = "java grey243";
          //String s = "java64 is12"; //Test string
          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
*/


So in this core java programming tutorial we Find sum of all even digits in string in java.


Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.



Related >













eEdit
Must read for you :