Sorry if the title is misleading or is confusing, but here is my dilemma. I am inputting a string, and want to assign a value to each capitalized letter in the alphabet (A=1, .. Z=26) and then add the values of each letter in that string.
Example: ABCD = 10 (since 1 + 2 + 3 + 4)
But I don't know how to add all the values in the string
NOTE: This is only for capitalized letters and strings
public class Test {
public static void main(String[] args) {
Scanner scannerTest = new Scanner(System.in);
System.out.println("Enter a name here: ");
String str = scannerTest.nextLine();
char[] ch = str.toCharArray();
int temp_integer = 64;
for (char c : ch) {
int temp = (int) c;
if (temp <= 90 & temp >= 65){
int sum = (temp - temp_integer);
System.out.println(sum);
}
}
}
}
So, as you can see I print out the sum for each time its looped, meaning: if I input "AB", the output will be 1 and 2.
However, I want to go a step further, and add these two values together, but I'm stumped, any suggestions or help? (NOTE: this is not a assignment or anything, just practising problem sets)
Using 64 to represent the character before 'A' in the ascii table is difficult to understand, you can perform substration between characters in Java directly.
So if 'A' represent 1, then just do c - 'A' + 1 will give you the corresponding integer value for each capitalized letter.
To get the sum, just sum up: initialize the sum as 0, and in the for loop, add increment sum by the value you calculated. You can use the incremental assignment operation: +=
Change only your for to these:
The
sum += (int) ch[i] - 96;
is because the chara
is the value 97, as your say, you want char a corresponde to 1, note thata
is different thanA
Check the char value here: https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html
This was tested and worked fine! Good Luck
I would prefer to use the character literals. You know that the range is
A
toZ
(1
to26
), so you can subtract 'A' from eachchar
(but you need to add 1 because it doesn't start at0
). I would also calltoUpperCase
on the input line. Something like,Which I tested with your example
It would look something like this (in C programming language) which you can easily modify for other programming languages:
The trick is to take the character value, subtract the baseline 'A' value and add 1 to arrive at your calculation range:
Achieve the same in a concise way by employing Java 8's lambda functions