很抱歉,如果标题具有误导性或令人困惑,但这是我的困境。 我正在输入一个字符串,并且想要为字母表中的每个大写字母分配一个值(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
),因此您可以减去“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:
ABCD
The sum of ABCD is 10
关于java - 如何获得循环中产生的 char 值的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33182304/