Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ASCII sum value of all characters

why does my code fail? It fails on the chatAt function upon the second rotation of the for loop.

public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int n = Integer.parseInt(scanner.nextLine());
        int sum = 0;

        for (int i = 0; i <n ; i++) {{
            String letter = scanner.nextLine();

            char valueOf = letter.charAt(i);
            int valueto = (int)valueOf;
            sum += valueto;
        }
        }
        System.out.println(sum);

    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Your code is getting the character from ith index, which will throw an index out of range error, as i increases continuously throughout the loop.

public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = Integer.parseInt(scanner.nextLine());
        int sum = 0;
        for (int i = 0; i <n ; i++) {{
            String letter = scanner.nextLine();
            // Set charAt 0th index to read the character from the input 
            char valueOf = letter.charAt(0);
            int valueto = (int)valueOf;
            sum += valueto;
        }
        }
        System.out.println(sum);

    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading