Reputation: 309
I am trying to write a Vigenere cipher decipher in java but i am getting some weird errors. Here is a high level explanation of what my code does.
My class takes an integer at initialization along with a number and two strings the message and the key.
It then proceeds to make a cyclic key of the same length as the message from the key.
After that it creates a string table with its first entry the "alphabet"in our case all characters from ascii (32 to 123) and the subsequent entries being the cyclic shift of their directly previous one by some constant.It then proceeds to create a new string from the old and the cyclic key by matching each character of the message with the cyclic key (the character of the cyclic key being the pointer to row and the character from the message the pointer to column)
When i try to run it java outputs some weird errors can you help me fix it.(assume that the caesar object works as intended.
Here is the code:`
public class Vigenere implements Vigenerface {
String key,msg;
caesr c;
String t[];
Vigenere(int i,String m,String k){
key=k;
msg=m;
int ln=k.length();
c=new caesr(i);
t=new String[ln*100];
for(int j=ln;j<m.length();j++)
key=key+key.charAt(j%ln);
// System.out.print(key);
for(int j=32;j<123;j++)
t[0]=t[0]+(char)j;
for(int j=1;j<101;j++) {
t[j]=c.encrypt(t[j-1]);
// System.out.print(t[j]+"\n");
}
}
public String encrypt(String S){
String tt = null;
System.out.print("i am in ");
for(int j=0;j<S.length();j++){
int te=(int)(key.charAt(j));
System.out.print(te);
char temp=t[te].charAt((int)S.charAt(j));
tt=tt+temp;
}
return tt;
}
public String decrypt(String S){
int f=0;
String tt = null;
for(int j=0;j<S.length();j++){
int te=(int)(key.charAt(j));
for(int k=0;k<t.length;k++)
if (t[te].charAt(k)==(S.charAt(j))){ f=k; break;}
char temp=t[te].charAt(f);
tt=tt+temp;
}
return tt;
}
}
Errors:
Exception in thread "main" 104java.lang.NullPointerException at Vigenere.encrypt(Vigenere.java:33) at mainfile.main(mainfile.java:11)
the first one is on this line:
char temp=t[te].charAt((int)S.charAt(j));
Content of the key: just a random string given during the initialization of the class
Upvotes: 0
Views: 141
Reputation: 1327
The NullPointerException happens if you use a key, that's longer than one character and contains at least one character over 100 which is the 'd' (see http://www.asciitable.com/). If you use "x" as your key you'll see an ArrayIndexOutOfBoundExecption. Maybe you can fix this by
for(int j = 1;j <= 100 * ln; j++) {
...
}
However, I didn't really get what it's about. For the size of t the number of different character in key seems important rather than it's length. So is you only use us ascii characters in your key the length of t should be 128 even if your key contains 1000 characters, as us ascii has 128 different characters
Upvotes: 1