Reputation: 37
Scanner user_input = new Scanner( System.in );
String cipher_input = user_input.nextLine();
String[] arr_cipher_input = cipher_input.split("");
int[] arr_ctext = new int[cipher_input.length()];
for (int i = 0; i < cipher_input.length(); i++) {
arr_ctext[i] = (int) arr_cipher_input[i].charAt(i);
}
The above code takes an input and splits it into an array (e.g. "hello" becomes ["h","e","l","l","o"]) and then I attempt to convert the characters to their ascii values which is where it returns the error in the title. It correctly converts the first character every time and then stops on the second and I can't seem to figure out why. The array lengths seem to be the same so I'm not sure what I'm doing wrong. I'd appreciate any help. Thanks in advance!
Upvotes: 1
Views: 57
Reputation: 201409
You are creating a number of one character String
(s). But you are trying to access subsequent characters. There aren't any. Change charAt(i)
to charAt(0)
to fix. Like,
arr_ctext[i] = (int) arr_cipher_input[i].charAt(0);
or (more efficiently) skip the split
and access the characters in the input directly. Like,
String cipher_input = user_input.nextLine();
int[] arr_ctext = new int[cipher_input.length()];
for (int i = 0; i < cipher_input.length(); i++) {
arr_ctext[i] = (int) cipher_input.charAt(i);
}
Upvotes: 5