如何获取循环中生成的char值的总和?

对不起,如果标题有误导性或令人困惑,但这是我的困境。 我正在输入一个字符串,并希望为字母表中的每个大写字母分配一个值(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 = 65){ int sum = (temp - temp_integer); System.out.println(sum); } } } } 

所以,正如你所看到的那样,我打印出每次循环的总和,这意味着:如果输入“AB”,输出将为1和2。

但是,我想更进一步,将这两个值加在一起,但我很难过,有什么建议或帮助吗? ( 注意:这不是作业或任何事情,只是练习问题集)

我更喜欢使用字符文字。 你知道范围是AZ126 ),所以你可以从每个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 

使用64来表示ascii表中’A’之前的字符很难理解,您可以直接在Java中的字符之间执行替换。

因此,如果’A’代表1,那么只需执行c – ‘A’+ 1将为每个大写字母提供相应的整数值。

要获得总和,只需总结:将总和初始化为0,并在for循环中,按您计算的值添加增量和。 您可以使用增量分配操作: + =

 Scanner scannerTest = new Scanner(System.in); System.out.println("Enter a name here: "); String str = scannerTest.nextLine(); char[] ch = str.toCharArray(); int sum = 0; for (char c : ch) { sum += c - 'A' + 1; } System.out.println(sum); 

只将你的改为:

 int sum = 0; for(int i = 0; i < ch.length; i++){ sum += (int) ch[i] - 96; System.out.println(sum); } 

sum += (int) ch[i] - 96; 是因为char a是值97,正如你所说,你想要char对应1,注意aA不同

在这里检查char值: https //www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html

经过测试,工作正常! 祝好运

它看起来像这样(用C编程语言),你可以很容易地修改其他编程语言:

 #include  #include  #include  int main() { int i; char word[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; unsigned int sum = 0; unsigned int charVal; for (i=0; i < strlen(word); ++i) { charVal = word[i] - 'A' + 1; printf("Value of %c is %d\n", word[i], charVal); sum += charVal; } printf("Sum of %s = %d\n", word, sum); return(0); } 

诀窍是取字符值,减去基线'A'值并加1以得到你的计算范围:

 charVal = word[i] - 'A' + 1;