java - How to debug a "ArrayIndexOutOfBoundsException" in my rail fence cipher program? -
here entire program encryption , decryption using rail fence cipher. arrayindexoutofboundsexception
in last 4th line. please me understand , fix error.
import java.io.bufferedreader; import java.io.ioexception; import java.io.inputstreamreader; /* * change template, choose tools | templates * , open template in editor. */ /** * * @author pratheesh */ public class test { public void encrypt2(string line,int rail) { int shift=0,p=0,itr; for(int i=0;i<rail;i++) { p=i; if(i==0||i==rail-1) shift=((rail-2)*2)+2; itr=1; while(p<line.length()) { system.out.print(line.charat(p)); if(i!=0&&i!=rail-1) { shift=((rail*itr-itr)-p)*2; } p+=shift; itr++; } } } public void decrypt2(string line,int arr[]) { int ptr[]=new int[arr.length+1]; int p1=0,p2=0,p3=0,c=1; boolean chk=true; system.out.print(line.charat(ptr[p3]+p1)); ptr[p3]++; while(c<line.length()) { if(chk) { p1+=arr[p2]; p2++; p3++; } else { p1-=arr[p2]; p2--; p3--; } system.out.print(line.charat(ptr[p3]+p1)); c++; ptr[p3]++; if(p2==arr.length) { p2--; chk=false; } else if(p2==-1) { p2++; chk=true; } } } public static void main(string args[]) throws ioexception, arrayindexoutofboundsexception{ test obj=new test(); string line; int rail,arr[],temp; line="password"; rail=integer.valueof(2); temp=line.length()-rail; int spaces; if(temp%(rail-1)!=0) { spaces=(rail-1)-(temp%(rail-1)); if((temp/(rail-1))%2!=0) { spaces+=rail-1; } } else { spaces=temp%(rail-1); if((temp/(rail-1))%2==0) { spaces+=rail-1; } } for(int g=0;g<spaces;g++) line+=' '; obj.encrypt2(line,rail); //decryption temp=line.length()-rail; arr=new int[rail-1]; if((temp/(rail-1))%2==0) arr[0]=1+(temp/(rail-1))/2; else arr[0]=1+((temp/(rail-1))+1)/2; arr[1]=arr[0]*2-2; for(int i=2;i<rail-1;i++) arr[i]=arr[1] obj.decrypt2(line,arr); } }
when allocating new array, number in square brackets number of elements in array, not index of last element of array. if want array 2 elements, arr[0]
, arr[1]
, need say
arr = new int[2]; // or expression value 2
not
arr = new int[1]; // there 1 element, arr[0]
i suspect error because you're trying assign arr[1]
array has 1 element.
Comments
Post a Comment