为什么Java内部编译器和IndexOf()为字符串返回不同的索引?
我的文件包含:为什么Java内部编译器和IndexOf()为字符串返回不同的索引?,java,string,indexing,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编译器时,它返回: Code: compil
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++;
}
试试看{
int num[]={4};//行号
字符串[]值=新字符串[]{;“};//正确的解决方案
//字符串[]值1=新字符串[]{“ic”};//替换为
int[]StartIndex={99};
int[]EndIndex={99};
FileInputStream fs=newfileinputstream(“C:\\Users\\Antish\\Desktop\\MyC1.java”);
BufferedReader br=新的BufferedReader(新的InputStreamReader(fs));
FileWriter writer1=新的FileWriter(“C:\\Users\\Antish\\Desktop\\Test\u File1.txt”);
弦线;
字符串line1=null;
字符串done=null;
整数计数=0;
line=br.readLine();
计数++;
while(行!=null){
布尔存在=假;
对于(int index=0;index
创建一个数组,其中一个元素的值为99。我不确定您想做什么,但我想您可能希望这样:
int[] StartIndex = new int[99];
我猜指示的位置反映了解析器的位置,即使是虚拟的,也不是字符串中的实际索引。消息可能应该被读取为“我在该索引处期望得到一些东西,但什么也没有找到”。我建议您在调试器中逐步完成代码,以便更好地了解每一行的作用,并帮助您找到错误。请参阅:在教程/文档中。您似乎对语法感到困惑。@fge-那么我如何解决此问题。编译器是否也在计算文件中的空格?您需要理解其中的区别介于编译错误和异常之间。编译器错误指的是程序的源代码;异常指的是程序在执行时遇到的状态。没有理由期望任何编译器错误中出现的任何数字与异常消息中出现的任何数字相同。换句话说,您的问题不构成错误nse.ok完成,但索引仍超出范围。因为该行上甚至不存在索引99。Java编译器是否也在计算空格?
int[] StartIndex = new int[99];