为什么Java Internal Compiler和IndexOf()为String返回不同的索引?

时间:2013-01-12 13:51:57

标签: java string indexing

我的文件包含:

public class MyC {
public void MyMethod()
        {
            **System.out.println("My method has been accessed")** // ; is expected

            System.out.println("My method has been accessed");
}

}

当我在这个文件上调用Eclipse Compiler时,它会返回:

Code: compiler.err.expected
Kind: ERROR
Line Number: 4
End position: 99
Position: 99

然而,当我尝试插入缺少的字符串“;”在第4行的第99位,它得到“索引超出范围异常”。

我在文件中手动计数,文件中甚至没有索引99。如何解决此问题。

以下是我的程序取代特定位置:

try {



             int num[] = {4}; //Line Numbers

             String[] VALUES = new String[] {";"}; //Correct Solutions

             //String[] VALUES1 = new String[] {"ic"}; //To Replace With

             int [] StartIndex ={99};

             int [] EndIndex ={99};
             FileInputStream fs= new FileInputStream("C:\\Users\\Antish\\Desktop\\MyC1.java");
             BufferedReader br = new BufferedReader(new InputStreamReader(fs));

             FileWriter writer1 = new FileWriter("C:\\Users\\Antish\\Desktop\\Test_File1.txt");

             String line;
             String line1 = null;

             String done = null;
             Integer count =0;

             line = br.readLine();
             count++;

             while(line!=null){


                 boolean exists = false;
                 for(int index =0;index<num.length;index++){
                     if(count == num[index]){ //Line Count Equals



                             exists = true;
                             StringBuffer buf = new StringBuffer(line);

                             buf.replace(StartIndex[index], EndIndex[index], VALUES[index]);//Get Positions From Array oF Indexes
                             done = buf.toString();
                             writer1.write(done+System.getProperty("line.separator"));



                     }
                 }

                 if (!exists)
                     writer1.write(line+System.getProperty("line.separator"));

                 line = br.readLine();

                 count++;


                 }

当我运行上述程序时,我得到了这个:

enter image description here

该程序运行正常,并替换特定索引处的字符串。我担心的是为什么Java Compiler会从文件中返回如此重要的位置。

1 个答案:

答案 0 :(得分:1)

int [] StartIndex ={99};

使用一个值为99的元素创建一个数组。我不确定你要做什么,但我想你可能想要这个:

int[] StartIndex = new int[99];