This is the first complete solution to find the sum of digits from a given alpha numeric value by mainly using String and Character class methods along with regular expressions and exceptions.
import java.util.Scanner;
public class SumOfDigitsInString {
public static void main(String[] args) {
Scanner inpStr = new Scanner(System.in);
System.out.println("Enter an alphanumeric value");
String inpLine = inpStr.nextLine();
/*
* Basic validations - Checking if the string is empty, if it contains more than
* one string, and if it's purely numeric & has any symbols
*/
if (inpLine.isEmpty())
System.out.println("Given string is empty");
else if (inpLine.split("\\s").length > 1)
System.out.println("Input can only contain one string");
else if (!isValidInput(inpLine))
System.out.println("The input should be alphanumeric or alphabetic");
else {
int digitSum = 0;
digitSum = sumOfDigits(inpLine);
inpStr.close();
System.out.printf("The sum of all the digits in the string is %d", digitSum).println();
}
}
private static boolean isValidInput(String s) {
/*
* This method uses regular expressions to check if the input string is valid by
* checking if it only contains digits and if it has any symbols. If it doesn't
* purely consist of digits AND doesn't contain symbols, this method returns
* true i.e. the input is valid.
*/
boolean onlyDigitChecker = s.matches("[0-9]*$") && s.matches("[^a-zA-Z]*$");
boolean noSymbolChecker = s.matches("^[a-zA-Z0-9]*$");
if (!onlyDigitChecker && noSymbolChecker)
return true;
else
return false;
}
private static int sumOfDigits(String s) {
/*
* This method runs through the input string and whenever it encounters a digit,
* it adds it to a variable. This variable, which is the sum of digits in the
* strings, is returned at the end
*/
int digitAdder = 0;
try {
for (int i = 0; i < s.length(); i++) {
char readChar = s.charAt(i);
if ((int) readChar >= 48 && (int) readChar <= 57)
digitAdder += ((int) readChar - 48);
}
} catch (Exception e) {
System.out.printf("Exception is %s", e).println();
}
return digitAdder;
}
}
Output 1:
Enter an alphanumeric value
World123
The sum of all the digits in the string is 6
Output 2:
Enter an alphanumeric value
Hello
The sum of all the digits in the string is 0
Output 3:
Enter an alphanumeric value
Hello World
Input can only contain one string
Output 4:
Enter an alphanumeric value
1234'].
The input should be alphanumeric or alphabetic

Leave a comment