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:


Sample Output 1:


Sample Input 2:


Sample Output 2:


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();


  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) {
    } else

Add a Comment

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

eighteen + eighteen =