How to get sum of char values produced in a loop?
Solution 1
I would prefer to use the character literals. You know that the range is A
to Z
(1
to 26
), so you can subtract 'A' from each char
(but you need to add 1 because it doesn't start at 0
). I would also call toUpperCase
on the input line. Something like,
Scanner scannerTest = new Scanner(System.in);
System.out.println("Enter a name here: ");
String str = scannerTest.nextLine().toUpperCase();
int sum = 0;
for (char ch : str.toCharArray()) {
if (ch >= 'A' && ch <= 'Z') {
sum += 1 + ch - 'A';
}
}
System.out.printf("The sum of %s is %d%n", str, sum);
Which I tested with your example
Enter a name here:
ABCD
The sum of ABCD is 10
Solution 2
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: +=
Scanner scannerTest = new Scanner(System.in);
System.out.println("Enter a name here: ");
String str = scannerTest.nextLine();
char[] ch = str.toCharArray();
int sum = 0;
for (char c : ch) {
sum += c - 'A' + 1;
}
System.out.println(sum);
data_pi
Updated on June 14, 2022Comments
-
data_pi almost 2 years
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)