This program I'm making isn't compiling right, I keep getting the error: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -9 at java.lang.String.charAt(String.java:687) at pro1.main(pro1.java:161)
Here's my code:
import java.io.*;
import java.util.*;
public class pro1 {
static String str="";
static String str1="";
static int range=250;
static int length;
static String key="";
static String ep="";
static String pt="";
static char temp;
static int t,p,h;
static int r,x,y,z,w;
static Random generator = new Random();
static public String getContents(File aFile)
{
StringBuilder contents = new StringBuilder();
try {
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null;
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
str1=contents.toString();
return str1;
}
public static void main (String args[]) throws IOException {
File testFile = new File("/home/amritha/Desktop/sam.txt");
System.out.println("Original file contents: " + getContents(testFile));
System.out.println("message:"+str1);
String sbox="abcdefghijklmnopqrstuvwxyz";
length=str1.length()-1;
for(int i=0;i<length;i++)
{
t=(int)str1.charAt(i);
if(t==32)
{
int t1=32;
temp=(char)t;
}
else
{
range=generator.nextInt(26)+1;
temp=sbox.charAt(range);
}
key+=""+temp;
}
System.out.println("Key:"+key);
for(int i=0;i<length;i++)
{
t=(int)str1.charAt(i);
{
if(t==32)
{
t=32;
temp=(char)t;
}
else
{
t-=97;
}
}
p=(int)key.charAt(i);
{
if(p==32)
{
p=32;
temp=(char)p;
}
else
{
p-=97;
}
}
if((t==32)&&(p==32))
{
int v=32;
temp=(char)v;
}
else
{
r=(t+p)%26;
temp=sbox.charAt(r);
}
ep+=""+temp;
}
System.out.println("Encrypted Text:"+ep);
for(int i=0;i<length;i++)
{
y=(int)ep.charAt(i);
{
if(y==32)
{
y=32;
temp=(char)y;
}
else
{
y-=97;
}
}
x=(int)key.charAt(i);
{
if(x==32)
{
x=32;
temp=(char)x;
}
else
{
x-=97;
}
}
if((x==32)&&(y==32))
{
int w=32;
temp=(char)w;
}
else
{
z=(y-x)%26;
temp=sbox.charAt(z);
}
pt+=""+temp;
}
System.out.println("deccrypted Text:"+pt);
}
}