3

Dismissing Scanner and prompts for the vigenere cipher I have:

for(int i = 0; i < text.length(); i++){
    int first = text.charAt(i);
    for(int j = 0; j < key.length(); j++){
        int second = key.charAt(j);
        int that = first + (second % 26);
        output = output + (char)that;
    }
}

My idea here for the vigenere cipher is to have one for-loop capture each character of the plaintext word. Then have the second for-loop capture each letter of the keyword. Where the plaintext "first" will represent the original position of the letter. Keyword will represent each individual shift of the plaintext characters. Will this be possible?

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Kissamer
  • 31
  • 1
  • Please indent your code properly so that it's readable. – Hovercraft Full Of Eels Feb 26 '16 at 03:33
  • .... I'll do it for you this time, but in the future, please put in this important effort yourself. – Hovercraft Full Of Eels Feb 26 '16 at 03:34
  • The key to solving this and similar problems is to experiment and try it out. So what happens when you try to do this? – Hovercraft Full Of Eels Feb 26 '16 at 03:35
  • @HovercraftFullOfEels just sort of hit a wall. I've been experimenting with it a lot. Different combinations. Thing is if I put in A for the text and A for the key so that would be A=65 in ASCII and then I have another A=65 for the key but then that's with 65%26 = 13 which would make sense because that would push the original A along the ASCII table to N which it does. But this isn't the case with other letters and I cannot figure out why – Kissamer Feb 26 '16 at 03:50
  • You first need to make sure that the characters start at A=0, B=1 etc., then you can perform modular arithmetic. Currently if `second % 26` = 25, then `first + (second % 26)` is probably out of range. – Maarten Bodewes Feb 26 '16 at 23:42

1 Answers1

0

Your problem is that you have 2 loops, but you should only have 1 loop.

Instead of a loop for the key, you should use modulous on the key length to give you the shift for that iteration.

Fixing the logic (and giving sensible names to variables):

for (int i = 0; i < text.length(); i++){
    int letter = text.charAt(i);
    int shift = key.charAt(i % key.length()) - 'A';
    int encrypted = (letter + shift) % 26 + 'A';
    output = output + (char)encrypted;
}

The main difference with this code and yours is the expression i % key.length(), which continuously cycles through the key's letters to determine the shift for each letter.

Bohemian
  • 412,405
  • 93
  • 575
  • 722