Java program to count the sum of numbers in a string

Count the sum of number in a string

For counting the sum of a digit in a given string, we’re going to code a java program in this article. Take a string input from the user and store it in a variable called “s” in this case. We are using isdigit method of Character class to check that particular character is a digit or not if that character is a digit then add that character to the sum variable to find sum.

 

java program to count sum of numbers in a string

Algorithm ​

  • Take a string input from user and store it in the variable called “s”.
  • Take a i for loop start from i=0 to i<s.length().
  • Check the condition that character is digit or not by using if(Character.isDigit(s.charAt(i))).
  • Calculate sum of each digit and store it in the sum variable.
  • After that simply print the value of sum.

Code in Java​

import java.util.Scanner;
public class SumOfAllNumbersPresentInTheString {
   public static void main(String[] args) {
   Scanner sc = new Scanner(System.in);
   System.out.print("Enter string : ");
   String s = sc.next();
   int sum=0;
   for (int i = 0; i < s.length(); i++) {
      if(Character.isDigit(s.charAt(i))) 
      sum=sum+Character.getNumericValue(s.charAt(i));
      }
   System.out.println("Sum of all the digit present in String : "+sum);
  }
}
This code is contributed by Shubham Nigam (Prepinsta Placement Cell Student)

Output

Enter string : pr2ep4in5st1
Sum of all the digit present in String : 12