我正在做一个将字符串句子转换成拉丁语的作业。我已经计划并编写了所有代码,但出现错误String索引超出范围。我认为第三个while循环增加了太多次,但是我不知道如何解决这个问题,或者甚至是问题所在。
感谢您的帮助。实际的Java错误在下面列出。
import java.util.*;
public class project1d {
public static void main(String[] args){
System.out.println("This is a pig latin translator. Enter a sentence to convert.");
Scanner console = new Scanner(System.in);
pigLat(console);
}
public static void pigLat(Scanner console){
String sentence = console.next();
int start = 0;
int end = 0;
int counter =0;
while(sentence.length()>0){
while(end<sentence.length()-1){
while(sentence.charAt(counter+1)!=' '){
counter++;
end = counter;
}
String word = sentence.substring(start,end);
int index= 0;
char letter= word.charAt(index);
while (letter != 'a' || letter != 'e' || letter != 'i' ||
letter != 'o' || letter != 'u'){
index++;
}
System.out.print(word.substring(index,word.length()-1)+"-");
System.out.print(word.substring(0,index-1)+"ay");
counter++;
start=end+1;
}
System.out.println("Do you wanna put in another? Press ENTER to quit");
sentence = console.next();
}
}
}
您正在增加索引并检查其值,而不确认该索引是否有效。
而且,在整个过程的第一次迭代之后,您不会在再次使用它们之前清除变量。请尝试:
while(sentence.length()>0){
start = 0; end = 0; counter = 0;
while(end<sentence.length()-1){
while(sentence.length()>counter+1 && sentence.charAt(counter+1)!=' '){
counter++;
end = counter;
}
String word = sentence.substring(start,end);
int index= 0;
char letter= word.charAt(index);
while (letter != 'a' || letter != 'e' || letter != 'i' ||
letter != 'o' || letter != 'u'){
index++;
}
System.out.print(word.substring(index,word.length()-1)+"-");
System.out.print(word.substring(0,index-1)+"ay");
counter++;
start=end+1;
}
System.out.println("Do you wanna put in another? Press ENTER to quit");
sentence = console.next();
}