Java String.substring()中的StringIndexOutOfBoundsException
我的代码一直有问题。它工作正常,做了它应该做的事情,但是当它完成某一段时会抛出这个错误,之后不会继续程序的其余部分:Java String.substring()中的StringIndexOutOfBoundsException,java,Java,我的代码一直有问题。它工作正常,做了它应该做的事情,但是当它完成某一段时会抛出这个错误,之后不会继续程序的其余部分: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 42 at java.lang.Sting.substring(Uknown Source) at SimplifyBinary.main(SimplifyBinary.j
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 42
at java.lang.Sting.substring(Uknown Source)
at SimplifyBinary.main(SimplifyBinary.java:32)
我已经隔离了问题代码段并将其粘贴到这里:
try{
//Turn input text file (binaryfile) into String
String binarycode = new Scanner(new File(binaryfile)).next();
int psn1 = 0;
int psn2 = 2;
//While loop that scans input String and replaces contents every two characters
while (psn1 >= 0){
String read = binarycode.substring(psn1, psn2);
String convert1 = read.replace("1", "A");
String convert2 = convert1.replace("0", "B");
//Create new text file
File converted = new File("convert1-"+binaryfile);
//Write changes to new text file
BufferedWriter output;
output = new BufferedWriter(new FileWriter(converted, true));
output.append(convert2);
output.close();
//Add 2 to each psn to move on to the next two characters in String for next loop
psn1 = psn1+2;
psn2 = psn2+2;
//While loop repeats until psn1 returns -1 when the String ends
}
}
catch (IOException e){
}
我做错什么了吗?是否缺少某些内容或不应存在某些内容?代码正在尝试访问不属于集合的索引。(特别是调用
.substring()
时不属于字符串的字符)在调试器中运行代码时,哪一行会抛出错误?发生这种情况时的运行时值是什么?您在(psn1>=0)时执行,然后只增加psn1
。你什么时候认为这个条件不再是真的?这个错误并不罕见,这在你学习数组时是很常见的。如果您向我展示一个从未生成IndexOutOfBounds错误的开发人员,我将向您致敬。正如所指出的,您有一个无限循环,它最终将调用超过字符串长度的索引并抛出异常。请尝试检查psn2是否小于字符串的长度。代码正在尝试访问不属于集合的索引。(特别是调用.substring()
时不属于字符串的字符)在调试器中运行代码时,哪一行会抛出错误?发生这种情况时的运行时值是什么?您在(psn1>=0)
时执行,然后只增加psn1
。你什么时候认为这个条件不再是真的?这个错误并不罕见,这在你学习数组时是很常见的。如果您向我展示一个从未生成IndexOutOfBounds错误的开发人员,我将向您致敬。正如所指出的,您有一个无限循环,它最终将调用超过字符串长度的索引并抛出异常。请尝试检查psn2是否小于字符串的长度。