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

2020-04-14 08:54发布

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.

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);
        }   
      }
    }
}

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)

5条回答
Juvenile、少年°
2楼-- · 2020-04-14 09:17

Using 64 to represent the character before 'A' in the ascii table is difficult to understand, you can perform substration between characters in Java directly.

So if 'A' represent 1, then just do c - 'A' + 1 will give you the corresponding integer value for each capitalized letter.

To get the sum, just sum up: initialize the sum as 0, and in the for loop, add increment sum by the value you calculated. You can use the incremental assignment operation: +=

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);
查看更多
▲ chillily
3楼-- · 2020-04-14 09:24

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

查看更多
beautiful°
4楼-- · 2020-04-14 09:25

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);

Which I tested with your example

Enter a name here: 
ABCD
The sum of ABCD is 10
查看更多
女痞
5楼-- · 2020-04-14 09:25

It would look something like this (in C programming language) which you can easily modify for other programming languages:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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);
}

The trick is to take the character value, subtract the baseline 'A' value and add 1 to arrive at your calculation range:

charVal = word[i] - 'A' + 1;
查看更多
forever°为你锁心
6楼-- · 2020-04-14 09:26

Achieve the same in a concise way by employing Java 8's lambda functions

String str = "ABCD";
int sum = str.chars()
                .filter(c -> c >= 'A' && c <= 'Z')
                .map(c -> 1 + c - 'A')
                .reduce(0, Integer::sum);
查看更多
登录 后发表回答