我正在尝试运行以下 HillCipher 程序,但它在将 char 数组转换为 int 数组的行之后终止,并且在编译该代码后它显示空指针异常。如果我用 int 变量替换 int 数组,它工作正常,但是我需要在这段代码中使用 int 数组来加密数据:
try{
do//key
{
System.out.println("Enter Key of length 4 character : ");
sKey=(new BufferedReader(new InputStreamReader(System.in))).readLine();
cKey=new char[2][2];
}while(!checkKey());
}
catch(Exception e)
{}
}
boolean checkKey()
{
boolean flag=true;
if(sKey.length()!=4)
flag=false;
int k=0;
int temp;
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
cKey[i][j]=sKey.charAt(k);
k++;
iKey[i][j]=(int)cKey[i][j]; //program is terminated after this line
iKey[i][j]-=97;
if(cKey[i][j]<97 || cKey[i][j]>122)
{
flag=false;
break;
}
}
if(flag==false)
{
System.out.println("flag: "+flag);
break;
}
}
int d;
if((d=iKey[0][0]*iKey[1][1]-iKey[1][0]*iKey[0][1])==0)
flag=false;
if(flag==false)
System.out.println("Invalid Key!! ");
else
keygen(d);
return flag;
}
void keygen(int d)
{
if (d<0)
d*=-1;
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
if(i==0 && j==0)
iDKey[i][j]=iKey[1][1]/d;
else if(i==1 && j==1)
iDKey[i][j]=iKey[0][0]/d;
else
iDKey[i][j]=-iKey[i][j]/d;
}
}
}
String encrypt()
{
int l;
if(sPlainTxt.length()%2==0)
l=sPlainTxt.length();
else
l=sPlainTxt.length()+1;
int temp1,temp2,ans;
for(int i=0;i<l;i+=2)
{
temp1=(int)cPlainTxt[i]-97;
temp2=(int)cPlainTxt[i+1]-97;
ans=iKey[0][0]*temp1+iKey[0][1]*temp2;
System.out.println(ans);
ans%=26;
ans+=65;
cCipherTxt[i]=(char)ans;
cCipherTxt[i+1]=(char)((iKey[1][0]*temp1+iKey[1][1]*temp2)%26+65);
}
sCipherTxt=new String(cCipherTxt);
return sCipherTxt;
}
}