user7282043 user7282043 - 8 months ago 99
Java Question

The Creation of The Encryption Key for a Keyword Cipher in My Code (Java)

I was just wondering if I could get some help with a question involving keyword ciphers.

The following code is supposed to create the encryption key for a keyword cipher (the key that states how your input (let's say "this is a secret message") became ("qabp bp k poynoq hoppkdo")). The key is, therefore, a String or char array. My teacher had us use a char array. For the case above, the key would

, and the basic alphabet would correspond to this
, therefore
would become
, I would become
, and so on and so forth.

But, anways, back to the problem at hand, when I try to create the key, the first loop that you see below works perfectly fine adding in the keyword for the first values of the array; however, after this adding in the rest of the array (the rest of the alphabet not including or skipping the letters of the keyword) doesn't seem to work in the second loop.

I don't exactly know what I am doing wrong, but I would guess it would have to do with one of the if statements, or the java keyword (
) that I use in the loop. Because it appears that when I print the keyword
, it comes out to
leaving out the last seven letters of the alphabet instead of the letters that already occur in the word,

If you could help fix the code, or get me on the right track, that would be much appreciated. If you have an question on the question, fell free to ask in the comment section below/

Thank you so much for all your help!

public class Crytograph
private String in;
private String out;
//private int awayFrom;
private char [] keyword;
private String word;
public Crytograph(String input, String wordLY) // , int fromAway )
in = input.toLowerCase();
out = "";
awayFrom = fromAway;
word = wordLY;
keyword = new char[26];
int counter = 97;
int counter1 = 0;
for (int x = 0; x < word.length(); x++)
keyword[x] = word.charAt(x);
for (int i = word.length(); i < 26; i++)
if ((char)(counter) == keyword[counter1])
keyword[i] = (char)(counter);
if (counter1 == word.length())
counter1 = 0;

Answer Source

You're comparing each new character to a single character at index counter1. But you really need to compare it to all the characters in word. Even if you happen to find a match, continue; will still increment i, meaning your array will be missing one or more characters at the end. Try this instead:

char c = 'a' - 1;
for (int i = word.length(); i < 26; i++) {
    // loop until we find a char not contained in `word`
    while (word.contains(String.valueOf(++c)));
    keyword[i] = c;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download