2016-07-11 1 views
-2

Je faisais un programme où il comptait combien de fois chaque mot était utilisé dans un paragraphe aléatoire. Il compile, mais quand j'essaie de l'exécuter, il me donne un NullPointerException.Comment gérer cette exception NullPointerException?

Voici le code:

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

pas un doublon comme le problème spécifique 'StringTokenizer' n'est pas abordée là. C'est un problème de flux de contrôle. – Will

+0

Btw Mohit, votre problème est cette ligne 'c [i]. SetCount (1, test [i])', parce que votre tableau 'c' contient des éléments' null', pas des instances 'Count'. Répare ça. Veuillez également accepter la copie suggérée, car elle correspond à votre question ici. – Tom

+0

ouais j'oublié d'initialiser ces instances ... mon mauvais: O il semble fonctionner maintenant mais je reçois une sortie bizarre de: - Name = outCount = 143 –

Répondre

1

Le principal problème est, même si vous avez créé un tableau de Count[], vous n'avez pas réellement initialisé un objet Count() à chaque position dans le tableau.

Count[] c = new Count[size]; 

Ce tableau lui-même initialise le, mais il ne fonctionne toujours pas initialisé placer Count() objet à chaque position du tableau. Vous devez réellement créer et attribuer ces nouveaux objets avec new Count() comme ceci:

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

Un autre problème semble être ici:

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

boucle Vous en st.hasMoreTokens(), mais vous continuez à appeler st.nextToken()size fois, et la fin est atteinte.

Essayez ceci:

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

encore Exception même –

+2

'NoSuchElementException' (lancée par 'nextToken')! = 'NullPointerException' (rapporté par OP) .... ou écrit comme une question: comment cet extrait du code OPs devrait-il lancer une exception' NullPointerException' et comment votre code corrige-t-il cela? – Tom

+0

La boucle entière n'a pas beaucoup de sens. 'test [i]' ne sera pas non plus défini. – Fildor

1

Lorsque vous faites c[i].SetCount(.....) l'objet à c[i] n'a pas été initialisées avec new Count()