-2

So for school I have to write a program that implements a Caesar Cipher. I was doing this and it was going well, however, the encryption method itself is not working out how I planned.

For example, let's say we're going to encrypt the string "abc"

It goes in as:

abc

It comes out as:

bbc

Now, I know exactly which lines of code are causing this issue. The only problem is I don't exactly know how to fix it.

Here is my code:

public static void encrypt(String toencrypt)
{
    unencrypted = toencrypt.toLowerCase();
    char[] sEn = unencrypted.toCharArray();
    char[] enEd = new char[sEn.length];
    if(toencrypt.length() > 0)
    {

        for(int i = 0; i < ALPHABET.length; i++)
        {
            for(int j = 0; j < sEn.length; j++)
            {
                if(sEn[j] == ALPHABET[i])
                {
                    sEn[j] = CIPHERBET[i];
                }
               //Below is the 'if' statement causing the issue
                if(enEd[j] == 0)   
                {
                    enEd[j] = sEn[j];
                }

            }

        }    
            String bts = new String(enEd);

            encrypted = bts;

            System.out.println("The encrypted message is: " + encrypted);
    }
    else
    {
        System.out.println("Please enter a string: ");
    }

}

In case you are confused on any of the data types that are not explicitly stated in the method, here they are:

  • ALPHABET is a character array
  • CIPHERBET is also a character array

I will extremely appreciative of any and all help I can receive.

Thank you in advance.

  • Possible duplicate of [Java, How to implement a Shift Cipher (Caesar Cipher)](https://stackoverflow.com/questions/19108737/java-how-to-implement-a-shift-cipher-caesar-cipher) – Lino Mar 01 '19 at 10:53
  • If you don't have a predefined char set you can just use something like this: https://ideone.com/IuSIAJ – Lino Mar 01 '19 at 11:16
  • @Lino This is an extremely specific question. I highly doubt this. Also due to possible plagiarism of code I could not use another persons answer. – Gh0stwarr10r Mar 01 '19 at 19:11

1 Answers1

0

You can change the loop a little

 for(int i = 0; i < sEn.length; i++)
 {
    flag=0;
    for(int j = 0; j < ALPHABET.length; j++)
     {
          if(sEn[i] == ALPHABET[j])
          {
               enEn[i]=CIPHERBET[j];
               flag=1;
               break;
           }
      }
      if(flag==0)
          enEn[i]=sEn[i];
 }

We always run the outer loop as per the no. of characters in the string. As far as I have understood the question you need to convert the character if it is in your character array else you want to retain the existing value as of the previous string.

Hope it helps.

Mohd Akbar
  • 111
  • 5