Reputation: 41
I've wrote a simple cipher (not supposed to hard) that ciphers a given string by changing the characters to char and adding the index to chek to scramble the values. The problem is, when I decipher the code it cuts the last character. Now I'm sure this is a simple rookie mistake but I'm struggling to find the culprit.
Any help would be greatly appreciated!
public class Cipher {
public void cipher(String strArg) {
String placeholder = strArg;
System.out.println("Unciphered text: "+placeholder);
char[] charArg = placeholder.toCharArray();
char[] cipheredArg;
int lengthArg = charArg.length-1;
cipheredArg = new char[lengthArg];
System.out.print("Ciphered text: ");
for (int i = 0; i < lengthArg; i++) {
char current = charArg[i];
cipheredArg[i] = (char) (current + i);
System.out.print(cipheredArg[i]);
}
System.out.print("\nDeciphered text: ");
for (int i = 0; i < lengthArg; i++) {
char current = cipheredArg[i];
charArg[i] = (char) (current - i);
System.out.print(charArg[i]);
}
}
public static void main(String[] args) {
Cipher show = new Cipher();
show.cipher("The quick brown fox jumps over the lazy dog.");
}
}
The output is:
Unciphered text: The quick brown fox jumps over the lazy dog.
Ciphered text: Tig#uzojs)l}{?|/v??3~????9????>???B????G???
Deciphered text: The quick brown fox jumps over the lazy dog
As you can see the dot is missing in the deciphered text. Any ideas?
Upvotes: 0
Views: 70
Reputation: 324
You can do it in this way:
for (int i = 0; i < charArg.length; i++)
Becouse char array should be in length of 0..n-1, but looks it's n elements. Like, You have word "Hello" and array starts with element 0 which is "H" to 4 which is "o". And looks it's 5 elements. I hope it helps You out.
Upvotes: -1
Reputation: 150108
You are double-compensating for zero-based indexing in Java
This reduces the length to iterate by one
int lengthArg = charArg.length-1;
as does this due to the < operator
for (int i = 0; i < lengthArg; i++) {
The canonical fix would be to use the full length of the array and the < operator
int lengthArg = charArg.length;
// ...
for (int i = 0; i < lengthArg; i++) {
Upvotes: 2