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

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

提交回复
热议问题