This is the first solution to find the sum of digits from a given alpha numeric value by using String and Character class methods.
import java.util.Scanner;
public class SumofdgtsinAlphanumericValue {
public static void main(String[] args) {
// TODO Auto-generated method stub
@SuppressWarnings("resource")
Scanner inpAlphaNumeric= new Scanner(System.in);
//Input an alphanumeric value
System.out.println("Enter an alphanumeric value=");
String strValue=inpAlphaNumeric.next();
System.out.println("The String value is="+strValue);
//Find out the Length
float sumDigits=0;
int lenOfStr=strValue.length();
while (lenOfStr > 0) {
if (Character.isDigit(strValue.charAt(lenOfStr-1)))
sumDigits=sumDigits+Character.getNumericValue(strValue.charAt(lenOfStr-1));
lenOfStr=lenOfStr-1;
}
System.out.println("The sum of digits in the given string is "+strValue+" is="+sumDigits);
}
}
Output:
Enter an alphanumeric value=
a1n2k3
The String value is=a1n2k3
The sum of digits in the given string is a1n2k3 is=6.0

Leave a comment