In this tutorial, we will learn the java program to fetch the integers from the given strings and print the sum of integers digits present in the string.
Take any string as an input from the user and check for integers and if there are integers then return the sum of digits of integers.
For example
Case 1: If the user inputs the string ‘1%program897Language%’
Then the output should be ‘25’, where there is no character that is repeating.
Case 2: If the user inputs the string ‘123!python!@456*’
Then the output should be ‘21’, where there is no character that is repeating.
Java Program to Find Sum of Integers in the String
import java.util.*;
public class Main {
public static void main(String[] args) {
int sum = 0;
System.out.println("Java Program to calculate sum of integers in string");
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a String");
String str = sc.nextLine();
int len = str.length();
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {
sum = sum + Character.getNumericValue(str.charAt(i));
}
}
System.out.println("Sum=" + sum);
}
}
Output
Java Program to calculate sum of integers in string
Please enter a String
Hitechp12345oint89s
Sum=32
Explanations
In this example, the user input the string ‘Hitechp12345oint89s’. While iterating the character of the string, the digits were found using the isdigit() method and when this happens the if block start executing which is taking the sum of digits. Finally, the program will return the sum of those digits as the output of the program which is 32.