Reputation: 85
This substitution cipher is supposed to scramble the alphabet and encode a message by finding the position of the letters in the message in the normal alphabet and substituting it with letters in the same position in the scrambled alphabet.
So a message like "ABC", using a scrambled alphabet like "QWERTYUIOPASDFGHJKLZXCVBNM" will become "QWE".
My problem is that the punctuation and spaces get replaced by other letters and each letter doesn't actually correspond to it's actual position, it's always one place after where it should be. The second part is a little puzzling but not a big issue.
Here's my code:
public static String cryptocodeM(String msg) {
String[] alphabetArray = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String newMsg = "";
List<String> list = Arrays.asList(alphabetArray);
Collections.shuffle(list);
StringBuffer alph2 = new StringBuffer();
for (int i = 1; i < list.size(); i++) {
alph2.append(list.get(i));
}
String scramb = alph2.toString(); //the scrambled alphabet
System.out.println(scramb);
msg = msg.toUpperCase();
for (int x = 0; x < msg.length(); x++) {
char a = msg.charAt(x); // the letters in msg
int index = alphabet.indexOf(a) + 1; // index of the letters in the alphabet //when I don't add 1 here I get a runtime error saying "String out of range -1"
char b = scramb.charAt(index); //finds letters in the same postion in the scrambled alphabet
newMsg += b; //Adds up the letters
}
return newMsg;
}
At this point, I have no clue on how to go about this, since I just started learning about strings. I would really appreciate it if you could help out.
Upvotes: 1
Views: 473
Reputation: 6329
The index
of -1
means that the search did not found it. See: String.indexOf()
Try something like this:
private static final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final char[] scramb = alphabet.toChararray();
public static String cryptocodeM(String msg)
{
if (null == msg || msg.isEmpty() )
return msg;
final StringBuilder newMsg = new StringBuilder(msg.length());
shuffleArray(scramb);
System.out.println(new String(scramb));
msg = msg.toUpperCase();
for (int x= 0; x < msg.length(); x++)
{
char a = msg.charAt(x);
final int index = alphabet.indexOf(a);
if (index > -1)
a = scramb[index];
newMsg.append(a);
}
return newMsg.toString();
}
public static void shuffleArray( char[] array )
{
final Random rnd = new Random();
for ( int i = array.length - 1 ; i > 0 ; --i )
{
final int index = rnd.nextInt( i + 1 );
// Simple swap
final char a = array[index];
array[index] = array[i];
array[i] = a;
}
}
The problem was, char[]
vs T...
, that is array of primitives vs array of objects... so i just looked up a shuffle from SO, and found this: Random shuffling of an array
Upvotes: 1