I need to change a string by shifting each letter by 3 (so “hello” would become “khoor”). I want to get the ASCII value of each character, add 3 to that integer, and convert the new integer back into a letter. I have scoured the internet and found answers that seem reasonable: use the string method toCareArray, loop through the characters and use the getNumericValue method, then add 3 to this number, then use (char)number.
These things are not working for me. My character array for “hello” becomes[C@75b84c92. (Strangely, my loop does not loop through [C@75b84c92, it loops through “hello”, so that’s nice I guess.) My getNumericValue for ‘h’ is 17. My char c = (char)number doesn’t work because numbers 0-32 in ASCII are invisible characters. I keep searching over and over again and using a lot of different sites, and they all suggest the above methods. Why is getNumericValue not giving me ASCII values? Where are the integers they convert my characters into coming from? All help is much appreciated! Here is my code:
public static String encrypt(String message, int shift) {
if (shift > 26){
return null;
}
String newMessage = "";
char [] chars = message.toCharArray();
for (char c: chars){
if (!Character.isLetter(c)) {
return null;
}
else {
int numericValue = Character.getNumericValue(c);
int newNumber = numericValue + shift;
char newChar = (char)newNumber;
newMessage += newChar;
}
}
return newMessage;
}
I used several websites and existing Stack Overflow questions and used the methods Character.getNumericValue(char) and (char)int. I expected to return the string “khoor” and instead returned what appears to be nothing because my numeric values converted into invisible characters.