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, ..
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