How to get sum of char values produced in a loop?

后端 未结 5 1117
迷失自我
迷失自我 2021-01-22 09:45

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, ..

5条回答
  •  隐瞒了意图╮
    2021-01-22 10:08

    Change only your for to these:

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

    The sum += (int) ch[i] - 96; is because the char a is the value 97, as your say, you want char a corresponde to 1, note that a is different than A

    Check the char value here: https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html

    This was tested and worked fine! Good Luck

提交回复
热议问题