2016-07-11 6 views
-2

Я делал программу, где он подсчитывал, сколько раз каждое слово использовалось в случайном абзаце. Он компилируется, но когда я пытаюсь запустить его, он дает мне NullPointerException.Как справиться с этим NullPointerException?

Вот код:

import java.util.StringTokenizer; 

class Count 
{ 
    int count; 
    String name; 

    void SetCount(int c, String n) 
    { 
     count = c; 
     name = n; 
    } 

    void Show() 
    { 
     System.out.print("Name=" + name); 
     System.out.print("Count=" + count); 
    } 
} 

class Contains2 extends Count 
{ 
    public static void main(String args[]) 
    { 
     String s = "Once you have made it to the box office and gotten your tickets, you are confronted with the problems of the theater itself. If you are in one of the run-down older theaters, you must adjust to the musty smell of seldom-cleaned carpets. Escaped springs lurk in the faded plush or cracked leather seats, and half the seats you sit in seem loose or tilted so that you sit at a strange angle. The newer twin and quad theaters offer their own problems. Sitting in an area only one-quarter the size of a regular theater, moviegoers often have to put up with the sound of the movie next door. This is especially jarring when the other movie involves racing cars or a karate war and you are trying to enjoy a quiet love story. And whether the theater is old or new, it will have floors that seem to be coated with rubber cement. By the end of a movie, shoes almost have to be pried off the floor because they have become sealed to a deadly compound of spilled soda, hardening bubble gum, and crushed Ju-Jubes"; 
     int size, i, count = 0, j; 

     size = s.length(); 
     String[] test = new String[size]; 

     Count[] c = new Count[size]; 

     StringTokenizer st = new StringTokenizer(s, " "); 

     while (st.hasMoreTokens()) 
     { 
      for (i=0; i < size; i++) 
      { 
       test[i] = st.nextToken(); 
       c[i].SetCount(1, test[i]); 
      } 
     } 

     for (i=0; i<size; i++) 
     { 
      for (j=0; j<size; j++) 
      { 
       if (c[i].name.equals(test[j])) 
        c[i].count+=1; 
      } 
     } 

     for (i=0; i<size; i++) 
     { 
      c[i].Show(); 
     } 
    } 
} 
+0

не дубликатом, как конкретная проблема с 'StringTokenizer' не рассматриваются там. Это проблема потока управления. – Will

+0

Btw Mohit, ваша проблема в этой строке 'c [i] .SetCount (1, test [i])', потому что ваш массив 'c' содержит элементы' null', а не 'Count'. Исправьте это. Также, пожалуйста, примите предложенный дубликат, так как он соответствует вашему вопросу здесь. – Tom

+0

да я забыл инициализировать эти экземпляры ... мой плохой: O это, кажется, работает сейчас, но я получаю странный вывод: - Name = outCount = 143 –

ответ

1

Основная проблема, несмотря на то, что вы создали массив Count[], вы на самом деле не инициировали Count() объекта в каждой позиции в массиве.

Count[] c = new Count[size]; 

Это инициализирует сам массив, но он по-прежнему не помещает инициализированный Count() объект в каждой позиции массива. Вы должны фактически создать и назначить эти новые объекты с new Count(), как это:

for (int i=0; i<size; i++) 
{ 
    c[i] = new Count(); 
} 

Еще одна проблема, кажется, здесь:

while (st.hasMoreTokens()) 
{ 
    for (i=0; i<size; i++) 
    { 
     test[i] = st.nextToken(); 
     c[i].SetCount(1, test[i]); 
    } 
} 

Вы петля в то время как st.hasMoreTokens(), но вы продолжаете вызова st.nextToken()size раз, и конец достигнут.

Попробуйте вместо этого:

import java.util.StringTokenizer; 


class Contains2 extends Count 
{ 
    public static void main(String args[]) 
    { 
     String s = "Once you have made it to the box office and gotten your tickets, you are confronted with the problems of the theater itself. If you are in one of the run-down older theaters, you must adjust to the musty smell of seldom-cleaned carpets. Escaped springs lurk in the faded plush or cracked leather seats, and half the seats you sit in seem loose or tilted so that you sit at a strange angle. The newer twin and quad theaters offer their own problems. Sitting in an area only one-quarter the size of a regular theater, moviegoers often have to put up with the sound of the movie next door. This is especially jarring when the other movie involves racing cars or a karate war and you are trying to enjoy a quiet love story. And whether the theater is old or new, it will have floors that seem to be coated with rubber cement. By the end of a movie, shoes almost have to be pried off the floor because they have become sealed to a deadly compound of spilled soda, hardening bubble gum, and crushed Ju-Jubes"; 
     int size, count = 0; 


     StringTokenizer st = new StringTokenizer(s, " "); 
     size = st.countTokens(); 

     Count[] c = new Count[size]; 
     String[] test = new String[size]; 

     while (st.hasMoreTokens()) 
     { 
      String token = st.nextToken(); 

      for (int i=0; i<size; i++) 
      { 
       test[i] = token; 

       c[i] = new Count(); 
       c[i].SetCount(1, token); 
      } 
     } 

     for (int i=0; i<size; i++) 
     { 
      for (int j=0; j<size; j++) 
      { 
       if (c[i].name.equals(test[j])) 
        c[i].count+=1; 
      } 
     } 

     for (int i=0; i<size; i++) 
     { 
      c[i].Show(); 
     } 
    } 
} 

public class Count 
{ 
    protected int count; 
    protected String name; 

    public void SetCount(int c, String n) 
    { 
     count = c; 
     name = n; 
    } 

    public void Show() 
    { 
     System.out.println("Name=" + name); 
     System.out.println("Count=" + count); 
    } 
} 
+0

еще же Exception –

+2

'NoSuchElementException' (брошенный 'nextToken')! =' NullPointerException' (сообщено OP) .... или написано как вопрос: как этот фрагмент кода OPs выдает «NullPointerException» и как ваш код исправляет это? – Tom

+0

Весь цикл не имеет большого смысла. 'test [i]' также не будет установлен. – Fildor

1

Когда вы c[i].SetCount(.....) объект в c[i] не отформатирован с new Count()

Смежные вопросы