How to get sum of char values produced in a loop?(如何获得循环中产生的 char 值的总和?)
问题描述
对不起,如果标题具有误导性或令人困惑,但这是我的困境.我正在输入一个字符串,并想为字母表中的每个大写字母(A=1,.. Z=26)分配一个值,然后添加该字符串中每个字母的值.
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.
示例: ABCD = 10(因为 1 + 2 + 3 + 4)
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);
}
}
}
}
所以,如您所见,我打印出每次循环的总和,含义:如果我输入AB",输出将是1和2.
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)
推荐答案
我更喜欢使用字符文字.你知道范围是A到Z(1到26),所以你可以减去'A'从每个 char 开始(但您需要添加 1,因为它不是从 0 开始的).我还会在输入行上调用 toUpperCase .类似的,
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);
我用你的例子测试过
Enter a name here:
ABCD
The sum of ABCD is 10
这篇关于如何获得循环中产生的 char 值的总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何获得循环中产生的 char 值的总和?
基础教程推荐
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- RabbitMQ:消息保持“未确认"; 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
