Write a java program to find Sum of Digits in a String.

Write code to get the sum of all the digits present in the given string.

Return the sum as the output. If there is no digit in the given string return -1 as output.

Input and Output Format:

Input consists of a string.

The output is a single integer which is the sum of digits in a given string.

Refer sample output for formatting specifications.

Sample Input 1:

good23bad4

Sample Output 1:

9

Sample Input 2:

good

Sample Output 2:

-1

Sum of Digits in a String 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 *

fifteen + 4 =