I'm currently working on a project in which I'm to create a Ceaser Cipher by taking a file as input and then requesting a number from the user. The number is to be used to shift letters forward, so if the number inputted was 2, a would become c. The alphabet is to wrap around (so if the letter is z and the input is 2, the ciphered letter would be b), and the program is to ignore non-letter characters and simply continue onward.
I've got a solution that I belive should work, but I think I'm missing something as the output is NOT what I expected nor what it should be. I've included the relevant section of code below
public static String encode(String content, int num){
char[] contentArray = content.toCharArray();
String encoded = "";
for(int i = 0; i < contentArray.length; i++){
char current = contentArray[i];
if (current >= 'a' && current <='z' || current >= 'A' && current <= 'Z'){
current = (char) (current + num);
if (current > 'z' | current > 'Z'){
current = (char) (current - 26);
} else if (current < 'a' | current < 'A'){
current = (char) (current + 26);
}
contentArray[i] = current;
encoded = encoded + encoded.concat(Character.toString(contentArray[i]));
} else {
i++;
}
}
return encoded;
}
Up above that is my main function, which simply asks the user for the necessary input before calling this function. In this case, the string content consists of the following characters: taco cat 1-349z 2
In theory, this should return vceq ecv 1-349b 2, if the user inputs 2 as num. Unfortunately that returns the following...
\I\IK\I\IKW\I\IK\I\IKWI\I\IK\I\IKW\I\IK\I\IKWI\\I\IK\I\IKW\I\IK\I\IKWI\I\IK\I\IKW\I\IK\I\IKWI\b
...which is obviously NOT correct. I have no idea what is going wrong in my code, so any assistance would be greatly appreciated. Thank you!
try this
public static String encode(String enc, int offset) {
offset = offset % 26 + 26;
StringBuilder encoded = new StringBuilder();
for (char i : enc.toCharArray()) {
if (Character.isLetter(i)) {
if (Character.isUpperCase(i)) {
encoded.append((char) ('A' + (i - 'A' + offset) % 26));
} else {
encoded.append((char) ('a' + (i - 'a' + offset) % 26));
}
} else {
encoded.append(i);
}
}
return encoded.toString();
}
Usage
System.out.println(encode("taco cat 1-349z", 2));