[英]StringIndexOutOfBoundsException
我正在制作的程序無法正確編譯,我不斷收到錯誤消息:線程“ main”中的異常java.lang.StringIndexOutOfBoundsException:字符串索引超出范圍:java.lang.String.charAt(String.java處為-9 :687)在pro1.main(pro1.java:161)
這是我的代碼:
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);
}
}
您的代碼在各個方面看起來都很混亂,我無法想象有人想要閱讀此代碼的170行。
看一下異常:它確切地告訴您出了什么問題:您將-9傳遞給charAt()作為索引,這-顯然-超出范圍,因為您只應在其中傳遞0 ...(length-1) 。
而且它也為您提供行號...所以轉到行號161,查看其中的內容以及到達那里的方式。
我的猜測是這與以下行有關:
z=(y-x)%26;
如果x大於y,則%運算的結果可能為負(或0)。 並且charAt(這是z作為參數給出的)期望為正值。 你應該試試:
z=Math.abs(y-x)%26;
編輯:作為旁注,通過查看其他人指出的異常或在最壞的情況下使用調試器並確切查看不同變量具有的值,應該不難自行解決以及為什么發生例外。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.