我的文件包括:爲什麼Java Internal Compiler和IndexOf()爲String返回不同的索引?
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編譯器對這個文件,它返回:
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++;
}
當我運行上面的程序,我得到這個:
程序工作正常並且在特定索引處替換字符串。我關心的是爲什麼Java編譯器從文件中返回如此大的位置。
我猜指示的位置反映瞭解析器的位置,即使是虛擬的,也不是字符串中的實際索引。該消息應該可以被讀爲「我期望在該索引處有東西,但什麼都沒有發現」。 – fge
我建議你逐步調試調試器中的代碼,以便更好地瞭解每一行的功能,並且這將幫助您找到該錯誤。 –
請參閱教程/文檔中的[創建,初始化和訪問數組](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html)。您似乎對語法感到困惑。 –