Given is the following String:
String s = "Qba'g sbetrg gb qevax lbhe Binygvar";
My desired output is:
Don't forget to drink your ovaltine
My code:
public static String decrpyt(String s){
String ans = "";
for (int i = 0; i<s.length(); i++) {
int x = s.charAt(i);
if (x <= 105) {
char c = ((char) (x + 13));
ans += c;
} else {
char c = ((char) (x - 13));
ans += c;
}
}
return ans;
}
It returns:
don4t-forget-to-drink-_our-ovaltine
What do I need to do to get the desired output?
答案 0 :(得分:1)
You are changing all characters, not just the letters, as has been mentioned in a comment. Carefully consider the range of characters that are letters that you need to modify. Declare x
to be a char
so that you don't have to consider the actual numeric ranges.
A-M => N-Z Action: += 13
a-m => n-z Action: += 13
N-Z => A-M Action: -= 13
n-z => a-m Action: -= 13
(all others) Action: No change
This can be expressed in 3 cases:
if ((x >= 'a' && x <= 'm') || (x >= 'A' && x <= 'M')) {
// Add 13
} else if ((x >= 'n' && x <= 'z') || (x >= 'N' && x <= 'Z')){
// Subtract 13
} else {
// Use as is
}
答案 1 :(得分:0)
You can add in an idea of exception characters. Basically any character in the exception list won't be translated. This would look something like:
public static String decrpyt(String s){
String ans = "";
for(int i = 0; i<s.length(); i++){
// Could use a list or whatever, just giving you the idea here
String characterAt = s.charAt(i).toString();
if(characterAt.equals("'") || characterAt.equals(" "))
{
continue;
}
int x = s.charAt(i);
if(x <= 105) {
char c = ((char) (x + 13));
ans += c;
}
else{
char c = ((char) (x - 13));
ans += c;
}
}
return ans;
}