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

后端 未结 5 1118
迷失自我
迷失自我 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

    0 讨论(0)
  • 2021-01-22 10:11

    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
    
    0 讨论(0)
  • 2021-01-22 10:15

    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);
    
    0 讨论(0)
  • 2021-01-22 10:15

    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;
    
    0 讨论(0)
  • 2021-01-22 10:15

    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);
    
    0 讨论(0)
提交回复
热议问题