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]
A more simpler solution to find the sum of all characters :
System.out.println("the ascii sum is " + word.chars().sum());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With