3

I'm stuck on some code for a class of mine. My professor encourages asking questions on forums such as this, especially since it gives him less questions :), so I figured I'd ask all of you for help.

The purpose of my assignment is to encrypt and decrypt and input string by shifting, or offseting, the characters over how of many times the user tells it to. My code is below.

For some reason, I got an error when I decrypt my encrypted text, and the error only occurs with numbers of 6 or more when run my code, so if used professor's example and encrypted "subterfuge" to offset 6 characters to make "yahzkxlamk" and then try to decrypt the text to offset 6 characters again to make "subterfuge", it gives me an error. The error is

java.lang.StringIndexOutOfBoundsException: String index out of range: -6

When I run the code with the same input string, "subterfuge", but with an offset of 5 or less, it works. The error is said to occur at the 65th line of the below code where it says

sb.append(alphabet.charAt(offset));

at the end of my Decrypt() method in the last else statement.

import javax.swing.*;

public class Encryptor {


private String plainText;
private int shift;
public String cipherText;


public Encryptor() {
    plainText = null;
    shift = 0;
}

public static void main(String[] args) {


    //encryption block
    Encryptor e = new Encryptor();
    String strCipherText = e.Encrypt();
    System.out.println("encrypted text");
    System.out.println(strCipherText);

    //decrypt block
    Encryptor d = new Encryptor();

    //cipher text becomes the input text to the Decrypt method
    d.cipherText = strCipherText;

    String strPlainText = d.Decrypt();
    System.out.println("decrypted text");
    System.out.println(strPlainText);

    System.exit(0);


}//end of main method

public String Decrypt()
{

            plainText = cipherText;

            shift = Integer.parseInt(JOptionPane.showInputDialog("enter offset"));

            int offset=0;
            int newOffset=0;
            String alphabet ="abcdefghijklmnopqrstuvwxyz";
            StringBuffer sb = new StringBuffer();
            int index = plainText.length();
            for(int i=0;i<index;i++)
            {
                String temp = "" + plainText.charAt(i);

                offset = alphabet.indexOf(temp);
                offset -= shift;
                if(offset > 25)
                {
                    newOffset = offset % 26;
                    sb.append(alphabet.charAt(newOffset));
                }
                else
                {
                    sb.append(alphabet.charAt(offset));
                }
            }//end of for loop
            return sb.toString();// return encrypted string
}

public String Encrypt()
{

    plainText = ((String)JOptionPane.showInputDialog("enter words " + "to encrypt")).toLowerCase().trim();


    shift = Integer.parseInt(JOptionPane.showInputDialog("enter offset"));

    int offset=0;
    int newOffset=0;
    String alphabet = "abcdefghijklmnopqrstuvwxyz";
    StringBuffer sb = new StringBuffer();
    int index = plainText.length();
    for(int i=0;i<index;i++)
    {
        String temp = "" + plainText.charAt(i);

        offset = alphabet.indexOf(temp);
        offset += shift;
        if(offset > 25)
        {
            newOffset = offset % 26;
            sb.append(alphabet.charAt(newOffset));
        }
        else
        {
            sb.append(alphabet.charAt(offset));
        }
    }//end of for loop
    return sb.toString();// return encrypted string
}

}

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
pHorseSpec
  • 1,246
  • 5
  • 19
  • 48
  • 3
    "My professor encourages asking questions on forums such as this, especially since it gives him less questions :)" Jesus are professors lazy now a day. – jgr208 Feb 06 '15 at 20:23
  • @jgr208 Not to mention StackOverflow is _not_ a forum. There's a post on meta somewhere discussing the _why_, but I'm too lazy to look. – Cole Tobin Feb 06 '15 at 20:56
  • @ColeJohnson yes i know, its like a community. since we arent on here to discuss stuff but answer stuff. – jgr208 Feb 06 '15 at 21:02

1 Answers1

4

Here is your problem:

offset = alphabet.indexOf(temp);
offset -= shift;
if(offset > 25)
{
    newOffset = offset % 26;
    sb.append(alphabet.charAt(newOffset));
}
else
{
    sb.append(alphabet.charAt(offset));//< New offset is less than 0
}

What you want is a positive-only mod function. So just add do this after you do your modular division:

while(newOffset < 0)
    newOffset += 26;

What I tend to do is just make a function for this:

/* Positive modular division. */
public static int pmod(int num, int mod)
{
    num %= mod;
    if(num < 0) num += mod;
    return num;
}
RealSkeptic
  • 33,993
  • 7
  • 53
  • 79
John
  • 3,769
  • 6
  • 30
  • 49
  • Actually, it's definitely not in the line you marked. That line is only executed for offsets that are bigger than 25, and thus, can't produce a negative remainder. The problem is in the `else`. – RealSkeptic Feb 06 '15 at 20:30