String.substring()

时间:2015-11-01 22:14:38

标签: 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.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){
}

我在这里做错了吗?是否有遗漏或有什么东西不应该存在?

0 个答案:

没有答案
相关问题