【发布时间】:2016-03-27 22:09:18
【问题描述】:
我正在制作的这个程序编译不正确,我不断收到错误: 线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:-9 在 java.lang.String.charAt(String.java: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);
}
}
【问题讨论】:
-
你不能只是把你的整个程序放在这里,然后指望有人通读整个程序并找到你的错误(特别是因为你甚至没有费心去标记抛出的行例外或正确格式化您的问题)。另外:如果程序抛出异常,它显然编译得很好。
-
你这里有一个错误:
length=str1.length()-1; for(int i=0;i<length;i++)。使用i<=length或length=str1.length();,否则你会错过最后一个字符。 (显然,这不是错误的原因) -
你对静态变量有一些疯狂的(ab)使用。你可能也想重构它。
-
顺便说一句。有一个叫做 debugger 的东西,你可以用它一步一步地检查你的代码并检查变量的值。
-
欢迎使用 stackoverflow sepp2k。我认为发布代码比问一些你可以谷歌的东西更好。