Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do find the sum of an ascii array?

I'm new to java (2 weeks) and I'm trying to convert a inputted string in to ascii code and trying to print the sum.

I've tried using IntStream.of(AsciiArray).sum but since its a string and not an int it doesn't work (Understandably)

import java.util.Arrays;
import java.util.Scanner;


public class Strings{

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a 5 letter word (all lower case): ");
        String word = input.nextLine(); 
        int length = word.length();
        byte[] bytes = word.getBytes(); 
        String AsciiArray = Arrays.toString(bytes);

        System.out.println("the ascii sum is" + AsciiArray);
    }

}

example of what I'm trying to do: "Enter a 5 letter word (all lower case): "

hello

the ascii sum is 532

what I get:

"Enter a 5 letter word (all lower case): "

hello

the ascii sum is [104, 101, 108, 108, 111]

like image 945
J WALKAZ Avatar asked Jan 01 '23 07:01

J WALKAZ


1 Answers

A more simpler solution to find the sum of all characters :

System.out.println("the ascii sum is " + word.chars().sum());
like image 71
Nicholas Kurian Avatar answered Jan 12 '23 00:01

Nicholas Kurian