2015-01-13 2 views
0

저는 프로그래머 애호가이며 약 한 달 동안 Java를 배우고 있습니다. 그래서, 나는 r/dailyprogramming을 통해 제공되는 문제에 착수하기로 결정했습니다. 링크는 관심있는 것들에 대한 아래 : Java 중첩 for-loop breaking abruptly

http://www.reddit.com/r/dailyprogrammer/comments/2nynip/2014121_challenge_191_easy_word_counting/

은 지금까지 나는 갈라라는 문자열 배열로 단어를 갈라있다. 단어는 모두 대소 문자와 마침표, 쉼표 및 다른 일반적인 구두점을 사용하여 소문자로 채워집니다. 현재 null이 아닌 배열의 첫 번째 단어를 가져 와서 각 요소를 확인하고 각 경우에 대해 계산하여 각 단어의 발생 수를 계산하려고합니다. 루프와 if 문을 중첩하여이 작업을 수행했습니다. 그러나 프로그램은 오류를 반환하지 않고 갑자기 중지합니다. 왜 누군가가 내 코드가 갑자기 멈추는 지 설명 할 수 있기를 바랍니다.

모든 부분이 코드의이 부분까지 제대로 작동합니다.

for (int i = 0; i < splitted.length; i++) { 

    if (splitted[i] != null) { 

     word = splitted[i]; 
     System.out.println("Word is: " + word); 

      for (int j = i; j < splitted.length; j++) { 

       if (splitted[j].contains(word)) { 

        splitted[j] = null; 
        count++; 
       } 
      } 

     System.out.println(word + ": " + count); 
     count = 0; 
    }   
} 

출력이 다른 수정 된 코드입니다. 내가 배열 길이를 확인하고 그것이 밖으로 바인딩되지 않습니다.

for (int i = 0; i < splitted.length; i++) { 

    if (splitted[i] != null) { 

     word = splitted[i]; 
     System.out.println("Word is: " + word); 

      for (int j = i; j < splitted.length; j++) { 

       System.out.printf("%d %s %B%n", j, splitted[j], splitted[j].contains(word)); 
       if (splitted[j].contains(word)) { 

        splitted[j] = null; 
        count++; 
       } 

       System.out.println(j + " is less than " + splitted.length); 
      } 

     System.out.println(word + ": " + count); 
     count = 0; 
    } 
     System.out.println(splitted[i] + " " + i);   
} 

편집보다 선명도 : 문제는 급격 splitted.length 미만 인 J 불구 배열 널 요소를 확인한 후 정지 프로그램이다.

출력 :

Today was great hello stupid Today. Today was bad. Today was amazing. He is great. He was bad. Now he is great! 
Word is: today 
0 today TRUE 
0 is less than 22 
1 was FALSE 
1 is less than 22 
2 great FALSE 
2 is less than 22 
3 hello FALSE 
3 is less than 22 
4 stupid FALSE 
4 is less than 22 
5 today TRUE 
5 is less than 22 
6 today TRUE 
6 is less than 22 
7 was FALSE 
7 is less than 22 
8 bad FALSE 
8 is less than 22 
9 today TRUE 
9 is less than 22 
10 was FALSE 
10 is less than 22 
11 amazing FALSE 
11 is less than 22 
12 he FALSE 
12 is less than 22 
13 is FALSE 
13 is less than 22 
14 great FALSE 
14 is less than 22 
15 he FALSE 
15 is less than 22 
16 was FALSE 
16 is less than 22 
17 bad FALSE 
17 is less than 22 
18 now FALSE 
18 is less than 22 
19 he FALSE 
19 is less than 22 
20 is FALSE 
20 is less than 22 
21 great FALSE 
21 is less than 22 
today: 4 
null 0 
Word is: was 
1 was TRUE 
1 is less than 22 
2 great FALSE 
2 is less than 22 
3 hello FALSE 
3 is less than 22 
4 stupid FALSE 
4 is less than 22 

감사합니다,

+0

출력 결과를 표시 할 수 있습니까? 코드가 멈추는 원인은 무엇이라고 생각하십니까? –

+0

split [j]가 null로 설정된 경우 (코드에서 발생), 다음에 splitted [j]가 발생할 때 null 포인터 예외에서 split [j] .contains (word)가 중지됩니다. – user2533521

+1

문법 경찰 : "split"은 단순 과거와 과거 분사가 "split"("split"되지 않음) 인 불규칙 동사입니다. – xpa1492

답변

0

문제는 당신이 당신의 for초 -loop에 null 확인하지 않는다는 것입니다 : 경우 null에서

for (int j = i; j < splitted.length; j++) { 
    if (splitted[j].contains(word)) {//what if splitted[j] is null? 
     splitted[j] = null; 
     count++; 
    } 
} 

가 발생합니다, 예를 들어 초기 반복에서 항목을 null으로 설정했기 때문에 하나는 NullPointerException.

그래서 당신은 사용해야

  • 당신은 아마 "foobarqux".contains("bar")true 때문에 equals가 대신 포함 사용해야합니다

    for (int j = i; j < splitted.length; j++) { 
        if (splitted[j] != null && splitted[j].contains(word)) {//what if splitted[j] is null? 
         splitted[j] = null; 
         count++; 
        } 
    } 
    

    완전히 잘하지 않습니다이 코드와 다른 측면이 있지만이 있습니다.

  • 카운트하기 전에 먼저 값을 정렬하거나 HashMap<String,Integer>을 사용하여 인스턴스를 더 효율적으로 계산할 수 있습니다 (O (n log n)).

확인하십시오. jdoodle.

+0

안녕하세요. 이것은 몇 가지를 명확히하지만 문제는 여전히 존재합니다. if 문 다음에 널 (null)을 만나서 검사합니다. if 문 끝에서 sys out 문을 사용하면 코드가 for 루프의 끝으로 진행되지만 j가 splitted.length보다 작음에도 for 루프를 다시 실행하지 않습니다. 당장은 널 포인터 예외 때문에 .equals/.contain 할 수 없다는 것을 받아 들였다. 대신 null 대신 "nu77"과 같은 abritrary String을 사용합니다. –

+0

@AaronLee : 작동하는 것으로 보이는 jdoodle로 업데이트되었습니다. –

+0

네가 맞아. 내 코드를 잘못 편집했거나 뭔가 추가하는 것을 잊어 버렸을 것입니다. 시간을내어 주셔서 감사합니다. null 검사는 오류를 반환하는 null을 건너 뛰는 데 실제로 도움이되었습니다. –