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
}
}