완전한 숙제를 위해 몇 가지 문자열 문제가 있습니다. 그것들은 모두 올바르게 작동하지만, 주 함수에서 그것들을 모을 때 문자열에서 가장 작은 단어를 찾은 마지막 단어는 오류를냅니다. 왜 그런지 알아?올바른 코드를 넣으면 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)
오류 메시지가 무엇입니까? 컴파일 오류 또는 런타임 예외입니까? 사람들이보다 쉽게 도움을 받도록하십시오. –
"스레드의 예외"메인 "java.lang.ArrayIndexOutOfBoundsException : 1 \t at StringFun.main (StringFun.java:77)" – Eric
@StevenMastandrea [숙제 태그는 이제 단계적으로 제거되어 더 이상 사용하지 않아야합니다. 사용할 수 있습니다] (http://meta.stackexchange.com/q/147100). – Gilles