2012-09-08 2 views
1

완전한 숙제를 위해 몇 가지 문자열 문제가 있습니다. 그것들은 모두 올바르게 작동하지만, 주 함수에서 그것들을 모을 때 문자열에서 가장 작은 단어를 찾은 마지막 단어는 오류를냅니다. 왜 그런지 알아?올바른 코드를 넣으면 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) 
+0

오류 메시지가 무엇입니까? 컴파일 오류 또는 런타임 예외입니까? 사람들이보다 쉽게 ​​도움을 받도록하십시오. –

+0

"스레드의 예외"메인 "java.lang.ArrayIndexOutOfBoundsException : 1 \t at StringFun.main (StringFun.java:77)" – Eric

+0

@StevenMastandrea [숙제 태그는 이제 단계적으로 제거되어 더 이상 사용하지 않아야합니다. 사용할 수 있습니다] (http://meta.stackexchange.com/q/147100). – Gilles

답변

3

이 줄은 예외를 던지는 것 같다 : 공백을 포함하지 않은 문자열 Sentence을 의미

shortestLengths=(myWords[1]).length(); 

그래서 myWords 두 번째 요소가 없어야을 (" ")를 나눌 수 있습니다. Sentencesc.nextLine()에서 왔기 때문에 "문제"가 입력되어야합니다. 그러나 실제로 문제는 제대로 처리하지 못한다는 것입니다. 각 단어에 걸쳐 반복하고 길이보다 작은 경우보고있는 이후 shortestLengthsInteger.MAX_VALUE로 시작 할 수없는 이유

이 그냥 논리에 반짝이기는하지만, 내가 볼 수 없습니다.

+0

왜 사전 편집 섹션이 자체적으로 작동하는지 설명 할 수 있습니까?하지만 나머지 프로그램과 함께 사용하면 설명하지 못합니까? – Eric

+0

'Sentence'는 궁극적으로'System.in'에서 나오므로 차이점은 여러분이 제공하는 입력과 반드시 ​​일치해야합니다. 단어와 문장 사이에 공백이있는 다른 입력을 시도해보십시오. 그러면 프로그램을 작성하지 않고 버그를 재현하는 데 도움이됩니다. –

1

shortestLengths=(myWords[1]).length(); 라인 77의 경우, 귀하의 의견은 거기에 공백이 없기 때문에 나는 그것을 말하고 싶지만, 당신이 확인하지 않습니다. 또한이 행에서 myWords [1]은 0이 첫 번째 색인이기 때문에 두 번째 단어를 참조합니다. 여기에있는 코드는 첫 단어를 완전히 무시합니다.

+0

첫 번째 단어는 건너 뛰기로되어있는 숫자이므로 의도 한대로 무시해야합니다. 이 프로그램은 그 자체로 작동하기 때문에 다른 프로그램과 함께 사용할 때 왜 작동하지 않는지 혼란 스럽습니다. – Eric

+0

@Eric 내가 가장 작은 단어 코드를 실행할 때, 단지 한 단어 만 줄 때 항상 실패합니다. 네가 두 단어로 그 벌금을 준다면. 왜 첫 단어를 건너 뛰는거야? 어쨌든,'Sentence.split ("");'이후에'if (myWords.length> 1) {...}'를 추가하면 충돌이 멈 춥니 다. 이렇게하지 않으면 인덱스에 액세스하지 못하게됩니다. –

+0

문자열 앞에 숫자를 입력해야하므로 숫자를 무시하는 방법을 찾을 수 없어서 두 번째 간격으로 검색을 시작하기로 결정했습니다. – Eric

관련 문제