我更喜欢使用字符文字。您知道范围是
A从
Z(
1到
26),因此您可以从每个范围中减去“ A”
char(但您需要加1,因为它的开头不是
0)。我还要
toUpperCase在输入行上打电话。就像是,
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);我用你的例子测试了
Enter a name here: ABCDThe sum of ABCD is 10



