I am trying to convert a given string into its ascii numerical value. My input will be coordinates such as "A1", "H3", "E8" etc.
This is my code:
public static void main(String[] args) {
String s = args[0];
char [] charArray = s.toCharArray();
int ascii = 0;
for (int i = 0; i < charArray.length; i ++) {
ascii = ascii + Character.getNumericValue(charArray[i]);
}
}
I was expecting the output for A1 to be 114 since (int) 'A' = 65 and (int) '1' = 49, however I am getting the result 11 for A1. How can I fix this?
Character.getNumericValue won't give you the ascii representation of the character.
A char
is just a positive 16-Bit integer containing the numeric representation of the character.
Therefore, you can just add the char
to the int
( ascii+=charArray[i];
).
[ Note ]
A char represents a Unicode-1 character and not an ascii character but it is backwards compatible.
I am trying to convert a given string into its ascii numerical value. My input will be coordinates such as "A1", "H3", "E8" etc.
This is my code:
public static void main(String[] args) {
String s = args[0];
char [] charArray = s.toCharArray();
int ascii = 0;
for (int i = 0; i < charArray.length; i ++) {
ascii = ascii + Character.getNumericValue(charArray[i]);
}
}
I was expecting the output for A1 to be 114 since (int) 'A' = 65 and (int) '1' = 49, however I am getting the result 11 for A1. How can I fix this?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.