【发布时间】:2020-09-28 01:03:29
【问题描述】:
我正在尝试制作一个程序,该程序将文本文件翻译成猪拉丁语。当我运行它时,它说线程“main”中的异常 java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-1。你能帮我修一下吗。我会告诉你代码中不正确的部分。
public static void piglatenizeFile(String fileNameIn, String fileNameOut)
{
Scanner infile = null;
String g = "";
String output = "";
String eachLetter = "";
int index= -1;
String vowels = "aeiouAEIOU";
try
{
infile = new Scanner(new File(fileNameIn));
}
catch(IOException e)
{
System.out.println("oops");
System.exit(0);
}
PrintWriter outfile = null;
try
{
outfile = new PrintWriter(new FileWriter(fileNameOut));
}
catch(IOException e)
{
System.out.println("File not created");
System.exit(0);
}
while(infile.hasNext()){// while txt has next line
String sentence = infile.nextLine();// looks at next line
String[] word = sentence.split(" ");//splits sentence to array of words
for(int i=0;i<word.length;i++){//goes through every word in the sentence
g =word[i].replaceAll("[\\p{Punct}]+", "");// replaces all punctuation
for(int t=0;t<g.length();t++){// goes through every letter in each word
eachLetter = g.substring(t,t+1);// eachLetter= each letter in noPunct
if(eachLetter == vowels){
index = t;
t = g.length();
}
}
output = g.substring(index)+ g.substring(0,index)+"ay";//ERROR
outfile.print(output+" ");
}
outfile.print("\n");
}
outfile.close();
infile.close();
}
}
【问题讨论】:
-
不要使用
==比较字符串。使用equals()。尽管在您的情况下,您应该像这样使用contains():if (vowels.contains(eachLetter)) -
我建议使用 Scanner 和 Tokenizer 来处理“单词”,而不是使用 for 循环。
标签: java