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

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

提交回复
热议问题