Write a java program to find Sum of Digits in a string

Write a Program that accepts a word as a parameter, extracts the digits within the string and returns its sum.

Input and Output Format:

Input consists of a string with maximum size of 100 characters.

The output consists of a single string.

Refer sample output for formatting specifications.

Sample Input 1:

abc12de4

Sample Output 1:

7

Find Sum of Digits in Java.

import java.util.Scanner;

public class Main {
  /**
   * @param args
   */
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String s1 = sc.nextLine();
    getvalues(s1);
  }

  public static void getvalues(String s1) {
    int sum = 0;
    for (int i = 0; i < s1.length(); i++) {
      char a = s1.charAt(i);
      if (Character.isDigit(a)) {
        int b = Integer.parseInt(String.valueOf(a));
        sum = sum + b;
      }
    }
    if (sum == 0) {
      System.out.println(-1);
    } else
      System.out.println(sum);
  }
}

 

Add a Comment

Your email address will not be published. Required fields are marked *

10 + seventeen =