Here are two solutions: one with a loop on demand and one with recursion. This works with both uppercase and lowercase letters, but does not account for non-alphabetic letters. This can be easily verified in an if-statement with the following criteria: Character.isAlphabetic( c ) .
public class Main { static final int LOWERCASE_OFFSET = 96; static final int UPPERCASE_OFFSET = 64; public static void main( String[] args ){ System.out.println(recursion( "Abcc" )); } static int recursion( String str ) { if( str.isEmpty() ) return 0; char c = str.charAt( 0 ); int charVal = Character.isUpperCase( c ) ? c - UPPERCASE_OFFSET : c - LOWERCASE_OFFSET; return charVal + recursion( str.substring( 1 ) ); } static int loop( String str ) { int val = 0; for( char c : str.toCharArray() ) { val += Character.isUpperCase( c ) ? c - UPPERCASE_OFFSET : c - LOWERCASE_OFFSET; } return val; } }
source share