抱歉,如果标题具有误导性或令人困惑,但这是我的困境。
我正在输入一个字符串,并希望为字母表中的每个大写字母(A=1,.. Z=26)分配一个值,然后添加该字符串中每个字母的值。
示例: ABCD = 10(因为 1 + 2 + 3 + 4)
但我不知道如何添加字符串中的所有值
注意 : 这仅适用于 大写 字母和字符串
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);
}
}
}
}
所以,正如你所看到的,我打印出每次循环的总和,
含义:如果我输入“AB”,输出将是 1 和 2。
但是,我想更进一步,将这两个值加在一起,但我很困惑,有什么建议或帮助吗? ( 注意: 这不是作业或任何东西,只是练习问题集)
最佳答案
我更喜欢使用字 rune 字。你知道范围是A
至Z
( 1
到 26
),因此您可以从每个 char
中减去“A” (但您需要添加 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:
ABCD
The sum of ABCD is 10
关于java - 如何获得循环中产生的 char 值的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33182304/