I am working on a radix sort lab for my college computer science B course but I keep running into an error. I need to get the value of a digit in a certain spot so to do that I converted the number into a string and used user charAt(2) to get the ones digit of 587. However, charAt is returning 55 which makes no sense and then I get an index out of bounds error because the number is supposed to be one digit from 0-9. the method takes the head of a linkedList, removes it from the linked list and then takes the removed node and adds it into a bucket.
String s = null;
String val;
for(int i = 0; i <count;i++){
int temp = (Integer)tempNode.getValue();
val = temp+"";
int dval = (int) val.charAt(mod);
tempNode =(name.removeFirst(s));
bucket[dval].addToEnd(tempNode);
tempNode = name.getHead();
}
What you're doing with (int) val.charAt(mod)
is getting the ascii value of the character, see this which is indeed 55
for the character 7
. What you want is Character.getNumericValue()
to get the numeric value of this character.
String str = "7";
System.out.println((int) str.charAt(0)); // Prints 55
System.out.println(Character.getNumericValue(str.charAt(0))); // Prints 7