У меня есть несколько проблем с строкой, которые мне нужно собрать для полного задания домашней работы. Они все работают правильно сами по себе, но когда я складываю их в основную функцию, последняя, которая находит наименьшее слово в строке, дает ошибку. Кто-нибудь знает, почему?Ошибка Java ArrayIndexOutOfBoundsException при создании правильного кода
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
//Length of Word
String word1 = sc.next();
System.out.println(word1.length());
//Evens in one string odds in the other
String word2 = sc.next();
StringBuilder even = new StringBuilder();
StringBuilder odd = new StringBuilder();
for(int i = 0; i < word2.length(); i++){
if(i % 2 == 0){
even.append(word2.charAt(i));
}
else{
odd.append(word2.charAt(i));
}
}
System.out.println(even + " " + odd);
//Diminishing Suffix
String word3 = sc.next();
for(int j = 0; j < word3.length(); j++){
System.out.print(word3.substring(j, word3.length()) + " ");
}
System.out.printf("\n");
//Letter Replacement
String word4 = sc.next();
String word5 = sc.next();
String word6 = sc.next();
String word7 = word4.replace(word5, word6);
System.out.println(word7);
//How many times x appears in xstring
String word8 = sc.next();
String word9 = sc.next();
int index = word8.indexOf(word9);
int count = 0;
while (index != -1) {
count++;
word8 = word8.substring(index + 1);
index = word8.indexOf(word9);
}
System.out.println(count);
System.out.println();
//Lexicographically smallest word
String Sentence = sc.nextLine();
String[] myWords = Sentence.split(" ");
int shortestLengths, shortestLocation;
shortestLengths=(myWords[1]).length();
shortestLocation=1;
for (int i = 1; i <myWords.length; i++) {
if ((myWords[i]).length() < shortestLengths) {
shortestLengths=(myWords[i]).length();
shortestLocation=i;
}
}
System.out.println(myWords[shortestLocation]);
}
}
Говоря о лексикографическом наименьшим. Ошибка дает это:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at StringFun.main(StringFun.java:77)
Какое сообщение об ошибке? Это ошибка компиляции или исключение во время выполнения? Постарайтесь облегчить людям помощь. –
он говорит «Исключение в потоке» main »java.lang.ArrayIndexOutOfBoundsException: 1 \t at StringFun.main (StringFun.java:77)" – Eric
@StevenMastandrea Обратите внимание, что [тег домашней работы в настоящее время постепенно прекращается и больше не должен (http://meta.stackexchange.com/q/147100). – Gilles