NullpointerException avec ActionPerformed

Fermé
Kimberley - Modifié par Kimberley le 8/05/2013 à 20:35
 Kimberley - 8 mai 2013 à 23:57
Bonjour,

J'ai un projet à rendre pour lundi et je suis débutante en java. Je ne peux pas avancer dessus étant donné que j'ai une exception qui apparaît à l'exécution de mon jeu :

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at GameEngine.interpretCommand(GameEngine.java:90)
at UserInterface.actionPerformed(UserInterface.java:185)



J'ai cherché un peu partout sur les forums et à chaque fois ils disent que c'est un problème d'instance mais je ne trouve pas le mien puisque les lignes correspondant à l'exception n'ont aucun rapport avec des objets j'ai l'impression (j'ai mis en gras et souligner les lignes correspondantes) : switch(vCommand) et engine.interpretCommand("back'');
Si vous pourriez vraiment m'aider ça serai génial, merci beaucoup!

pour la classe UserInterface

import javax.swing.*;  
import java.awt.*;  
import java.awt.event.*;  
import java.net.URL;  
import java.awt.image.*;  
import java.awt.event.ActionEvent;  
import java.awt.event.ActionListener;  


/**  
 * This class implements a simple graphical user interface with a text entry  
 * area, a text output area and an optional image.  
 */  
public class UserInterface implements ActionListener  
{  
    private GameEngine engine;  
    private JFrame myFrame;  
    private JTextField entryField;  
    private JTextArea log;  
    private JLabel image;  
    private JButton bouton1, bouton2, bouton3, bouton4, bouton5, bouton6, bouton7, bouton8, bouton11, bouton12, bouton13;  
      
    /**  
     * Construct a UserInterface. As a parameter, a Game Engine  
     * (an object processing and executing the game commands) is  
     * needed.  
     *   
     * @param gameEngine  The GameEngine object implementing the game logic.  
     */  
    public UserInterface(GameEngine gameEngine)  
    {  
        engine = gameEngine;  
        createGUI();  
    }  

    /**  
     * Print out some text into the text area.  
     */  
    public void print(String text)  
    {  
        log.append(text);  
        log.setCaretPosition(log.getDocument().getLength());  
    }  

    /**  
     * Print out some text into the text area, followed by a line break.  
     */  
    public void println(String text)  
    {  
        log.append(text + "\n");  
        log.setCaretPosition(log.getDocument().getLength());  
    }  

    /**  
     * Show an image file in the interface.  
     */  
    public void showImage(String imageName)  
    {  
        URL imageURL = this.getClass().getClassLoader().getResource(imageName);  
        if(imageURL == null)  
            System.out.println("image not found");  
        else {  
            ImageIcon icon = new ImageIcon(imageURL);  
            image.setIcon(icon);  
            myFrame.pack();  
        }  
    }  

    /**  
     * Enable or disable input in the input field.  
     */  
    public void enable(boolean on)  
    {  
        entryField.setEditable(on);  
        if(!on)  
            entryField.getCaret().setBlinkRate(0);  
    }  

    /**  
     * Set up graphical user interface.  
     */  
    private void createGUI()  
    {  
        myFrame = new JFrame("Zork");  
        entryField = new JTextField(34);  

        log = new JTextArea();  
        log.setEditable(false);  
        JScrollPane listScroller = new JScrollPane(log);  
        listScroller.setPreferredSize(new Dimension(200, 200));  
        listScroller.setMinimumSize(new Dimension(100,100));  

        JPanel panel = new JPanel();  
        image = new JLabel();  
          
        bouton1= new JButton ("Monter");  
        bouton2= new JButton ("Look");  
        bouton3= new JButton ("Droite");  
        bouton4= new JButton ("Descendre");  
        bouton5= new JButton ("Revenir");  
        bouton6= new JButton ("Gauche");  
        bouton7= new JButton ("Charge");  
        bouton8= new JButton ("Fire");  
        bouton11= new JButton ("help");  
        bouton12= new JButton ("quit");  
        bouton13= new JButton ("test");  
          
        JPanel panel2= new JPanel (new BorderLayout());  
          
        panel.setLayout(new BorderLayout());  
        panel.add(image, BorderLayout.NORTH);  
        panel.add(listScroller, BorderLayout.CENTER);  
        panel.add(entryField, BorderLayout.SOUTH);  
        panel.add(panel2, BorderLayout.EAST);  
          
        JPanel panel3= new JPanel (new BorderLayout());  
          
        panel2.add(bouton1, BorderLayout.NORTH);  
        panel2.add(bouton3, BorderLayout.EAST);   
        panel2.add(bouton4, BorderLayout.SOUTH);  
        panel2.add(bouton6, BorderLayout.WEST);  
        panel2.add(panel3, BorderLayout.CENTER);  
          
        JPanel panel4= new JPanel (new BorderLayout());  
          
        panel3.add(bouton11, BorderLayout.EAST);  
        panel3.add(bouton5, BorderLayout.SOUTH);  
        panel3.add(bouton2, BorderLayout. NORTH);  
        panel3.add(bouton12, BorderLayout. WEST);  
        panel3.add(panel4, BorderLayout.CENTER);  
          
        JPanel panel5= new JPanel(new BorderLayout());  
          
        panel4.add(bouton7, BorderLayout.EAST);  
        panel4.add(bouton8, BorderLayout.WEST);  
        panel4.add(bouton13, BorderLayout.NORTH);  
          
        panel4.add(panel5, BorderLayout.CENTER);  
          
         


          
        myFrame.getContentPane().add(panel, BorderLayout.CENTER);  

        // add some event listeners to some components  
        myFrame.addWindowListener(new WindowAdapter() {  
            public void windowClosing(WindowEvent e) {System.exit(0);}  
        });  

        entryField.addActionListener(this);  
        this.bouton1.addActionListener(this);  
        this.bouton2.addActionListener(this);  
        this.bouton3.addActionListener(this);  
        this.bouton4.addActionListener(this);  
        this.bouton5.addActionListener(this);  
        this.bouton6.addActionListener(this);  
        this.bouton7.addActionListener(this);  
        this.bouton8.addActionListener(this);  
        this.bouton11.addActionListener(this);  
        this.bouton12.addActionListener(this);  
        this.bouton13.addActionListener(this);  
         

          
        myFrame.pack();  
        myFrame.setVisible(true);  
        entryField.requestFocus();  
    }  

    /**  
     * Actionlistener interface for entry textfield.  
     */  
    public void actionPerformed(ActionEvent event)   
    { Object source= event.getSource();  
        if(source==bouton1)  
        engine.interpretCommand("go monter");  
      else if (source==bouton2)  
        engine.interpretCommand("look");  
      else if (source==bouton3)  
        engine.interpretCommand("go droite");  
      else if (source==bouton4)  
        engine.interpretCommand("go descendre");  
      else if (source==bouton5)  
        engine.interpretCommand("back");  
      else if (source==bouton6)  
        engine.interpretCommand("go gauche");  
      else if (source==bouton7)  
       engine.interpretCommand("charge");  
      else if (source==bouton8)  
       engine.interpretCommand("fire");    
      else if (source==bouton11)  
      engine.interpretCommand("help");  
      else if (source==bouton12)  
      engine.interpretCommand("quit");  
      else if (source==bouton13)  
      engine.interpretCommand("test");  
        
      else           
        processCommand();  
    }  

    /**  
     * A command has been entered. Read the command and do whatever is   
     * necessary to process it.  
     */  
    private void processCommand()  
    {  
         
        String input = entryField.getText();  
        entryField.setText("");  

        engine.interpretCommand(input);  
    }  
}  



et la classe GameEngine :

    
import java.util.Stack;  
import java.io.File;  
import java.util.Scanner;  
import java.util.Random;  
import java.util.ArrayList;  
import java.io.FileNotFoundException;  
import java.util.HashMap;  

public class GameEngine  
{  
    private Parser parser;  
    private Room currentRoom;  
    private Room previousRoom;  
    private UserInterface gui;  
    private Stack<Room> roomsHistory = new Stack<Room>();  
    private Choc choc;  
    private Room feu, four, premieregrille, deuxiemegrille, troisiemegrille, quatriemegrille, cinquiemegrille, verredelait, teleportation;  
    private int vDep=0;  
    private Room target;  
    

    private ArrayList<Room> rooms;  
    private Room randomRoom;  
    private static HashMap <String, Room> aListRoom;   
      

    /**  
     * Constructor for objects of class GameEngine  
     */  
    public GameEngine()  
    {  
        choc = new Choc("Choc la pépite ", 2);  
        parser = new Parser();  
        createRooms();          
         // start game outside  
        roomsHistory = new Stack<Room>();  
      
    }  
      
    public void setGUI(UserInterface userInterface)  
    {  
        gui = userInterface;  
        printWelcome();  
    }  

    /**  
     * Print out the opening message for the player.  
     */  
    private void printWelcome()  
    {   gui.print("\n");  
        gui.println("Bienvenue dans le four");  
        gui.println("Choc la pépite de chocolat est le jeu le plus angoissant qui existe");  
        gui.println("Tape 'help' si tu as besoin d'aide");  
        gui.print("\n");  
        gui.println(currentRoom.getLongDescription());  
        gui.showImage(currentRoom.getImageName());  
    }  
     
    private void charge() {  
        choc.chargeBeamer();  
        gui.println("Beamer chargé.");}  
          
         
    private void fire() {  
            if(choc.fireBeamer()) {  
                gui.showImage( choc.getRoom().getImageName() );  
                gui.println("Beamer fired.");  
                gui.println(choc.getRoom().getLongDescription());  
                roomsHistory= new Stack<Room>();  
            }  
            else {  
                gui.println("Beamer non chargé.");  
            }  
        }  
         
    /**  
     * An example of a method - replace this comment with your own  
     *  
     * @param  y   a sample parameter for a method  
     * @return     the sum of x and y  
     */  
    public void interpretCommand(String commandLine)   
    {  
        this.gui.println("\n" + commandLine);  
        Command vCommand = this.parser.getCommand(commandLine);  
        CommandWord vCommandWord = vCommand.getCommandWord();  

        switch (vCommandWord)  
        {  
            case UNKNOWN:  
                this.gui.println("Parle français s'il te plaît...");  
            break;  
              
            case HELP:  
                this.printHelp();  
            break;  
              
            case GO :  
                this.goRoom(vCommand);  
            break;  
              
            case LOOK:  
                this.look();  
            break;  
              
            case QUIT:  
                if(vCommand.hasSecondWord())  
                {  
                    this.gui.println("Quitter quoi?");  
                }  
                else  
                {  
                    endGame();  
                }  
            break;  
             
            case TEST:  
                this.test(vCommand);  
            break;  
              
            case POSER:  
                this.poser(vCommand);  
            break;  
              
            case BACK:  
           this.back(vCommand);  
      
            break;  
              
            case PRENDRE:  
                this.prendre(vCommand);  
            break;   
              
            case FIRE:  
                this.fire();  
            break;  
              
            case CHARGE:  
                this.charge();  
            break;  
              
            //case ALEA:  
              // this.alea(vCommand);  
           // break;  
              
            case ITEMS:  
                this.printItems();  
            break;  
        }  
    }  
     
    private void test (Command pCommand)  
    {  
        if(!pCommand.hasSecondWord())   
        {  
            // if there is no second word, we don't know what to test...  
            this.gui.println("Tester quoi? gagner.txt ou commande.txt?");  
            return;  
        }  
          
        Scanner vtest;  
          
        try   
        {   
            vtest = new Scanner( new File( "./" + pCommand.getSecondWord() ) );  
            while ( vtest.hasNextLine() )  
            {  
                String ligne = vtest.nextLine();  
                interpretCommand(ligne);  
            }  
            vtest.close();  
        }   
        catch ( FileNotFoundException pObjetException )   
        {    
            this.gui.println("le nom du fichier est incorrect");  
        }   
    }  

    /**  
     * Create all the rooms and link their exits together.  
     */  
    private void createRooms()  
    {  
        GameEngine.aListRoom = new HashMap <String, Room> ();   
        
        // create the rooms  
       four = new Room("dans le four","four.jpg");  
        feu = new Room ("mort, Tu as fais mourrir Choc","feu.jpg");  
        target = feu;  
        premieregrille = new Room("sur la première grille","eclairpate.jpg");  
        deuxiemegrille = new Room("sur la deuxième grille","eclair.jpg");  
        troisiemegrille = new Room("sur la troisième grille","gateau choco.jpg");  
        quatriemegrille = new Room ( " sur la quatrième grille","TARTE_POMMES.jpg");  
        cinquiemegrille= new Room ("sur la cinquième grille","poulet.jpg");  
        verredelait = new Room("dans le lait. Tu as sauvé Choc! :D ","verre de lait.jpg");  
        //teleportation = new Room ("dans la salle de téléportation. Trouve comment t'en sortir!","teleportation.jpeg");  
       
        //put items in the rooms  
        premieregrille.addItem(new Item("chaussure","chaussure  ", 1));  
         
        deuxiemegrille.addItem(new Item("energie", "boisson energisante, Choc est en pleine forme!   ", 6));  
        troisiemegrille.addItem(new Item("levure", " Levure blanche pour monter    ", 2));  
        quatriemegrille.addItem(new Item("chaussure", "chaussure  ", 5));  
        
        // initialise room exits  
        four.setExit("monter", premieregrille);  
        four.setExit("descendre", feu);  
        premieregrille.setExit("monter", deuxiemegrille);  
        premieregrille.setExit("droite", four);  
        premieregrille.setExit("descendre", feu);  
        premieregrille.setExit("gauche", four );  
        deuxiemegrille.setExit("monter", troisiemegrille);  
        deuxiemegrille.setExit("descendre", null);  
        deuxiemegrille.setExit("gauche", teleportation);  
        troisiemegrille.setExit("monter", quatriemegrille);  
        troisiemegrille.setExit("droite", four);  
        troisiemegrille.setExit("descendre", deuxiemegrille);  
        troisiemegrille.setExit("gauche", four);  
        quatriemegrille.setExit("monter", cinquiemegrille);  
        quatriemegrille.setExit("descendre", premieregrille);  
        cinquiemegrille.setExit("droite", four);  
        cinquiemegrille.setExit("descendre", premieregrille);  
        cinquiemegrille.setExit("gauche", verredelait);  
           

        
        currentRoom = four; // commencer le jeu dans le four  
          

        randomRoom= deuxiemegrille;  
        
          
        this.choc.setCurrentRoom(previousRoom);  
       
        GameEngine.aListRoom.put ("four", four);  
        GameEngine.aListRoom.put ("première grille", premieregrille);  
        GameEngine.aListRoom.put ("deuxième grille", deuxiemegrille);  
        GameEngine.aListRoom.put ("troisième grille", troisiemegrille);  
        GameEngine.aListRoom.put ("quatrième grille", quatriemegrille);  
        GameEngine.aListRoom.put ("cinquième grille", cinquiemegrille);  
        
         
    }  
      
    /**  
     *  Main play routine.Loops until end of play.  
     */  
    public void play(String commandLine)   
    {              
        printWelcome();  

        // Enter the main command loop.  Here we repeatedly read commands and  
        // execute them until the game is over.  
                  
        boolean finished = false;  
        while (! finished) {  
            //Command command = parser.getCommand(commandLine);  
            //finished = processCommand(command);  
            if(choc.getCurrentRoom() == feu) {  
                printMort();  
                finished = true;  
            }  
              
            if(choc.getCurrentRoom() == verredelait ) {  
                printSauver();  
                finished = true;  
            }  
        }  
        System.out.println("merci d'avoir jouer!");  
    }  
      
     private void printMort() {  
        gui.println("\nTu as perdu. Choc est mort.");  
    }  
      
    private void printSauver() {  
        gui.println("\nTu as sauvé Choc! Bravo!");  
    }  
      
      
   public void back(Command command)  
 {  
     if ( command.hasSecondWord() ) {  
         gui.println( "Sorry, but the Back command has no second word on it" );  
      return;  
        }  
        else  
        if ( previousRoom == null ) {  
            gui.println( "Sorry but you are at the begining of the game you can't got further back" );  
            return;  
        }  
    else {  
            choc.setCurrentRoom(roomsHistory.pop());  
            gui.println(choc.getCurrentRoom().getLongDescription());  
            if(choc.getCurrentRoom().getImageName() !=null)  
            gui.showImage(choc.getCurrentRoom().getImageName());  
              
        }  
    }  
           
     

    /**  
     * Print out some help information.  
     * Here we print some stupid, cryptic message and a list of the   
     * command words.  
     */  
    private void printHelp()   
    {  
         gui.println("Tu es perdu. Tu es seule, toute seule... Tu angoisses");  
        gui.println("Indice pour te pretrouver: retape le mot");  
          
        gui.println("Courage! Tu y es presque");  
        gui.println("Ne pars pas! Choc va mourir! Tente.. go, help ou quitter");  
        gui.println("Vos commandes sont : ");  
        parser.showCommands();  
         
    }  
     
    /**   
     * Try to go to one direction. If there is an exit, enter the new  
     * room, otherwise print an error message.  
     */  
    private void goRoom(Command command)   
    {  
         
       if (vDep<4)   
        {  
            vDep++;  
              
        }  
        else {  
              
            choc.estMort();  
            this.printMort();   
           this.endGame();  
                
        }  
      
           
        if(!command.hasSecondWord()) {  
            // if there is no second word, we don't know where to go...  
            gui.println("Où veux tu aller?");  
            return;  
        }  

        String direction = command.getSecondWord();  

        // Try to leave current room.  
        Room nextRoom = currentRoom.getExit(direction);  

        if (nextRoom == null)  
            gui.println("Impossible");  
        else {  
          roomsHistory.push(currentRoom);  
         enterRoom(nextRoom);  
            if(currentRoom.getImageName() != null)  
                gui.showImage(currentRoom.getImageName());  
        }  
        
    }  
          
      
    /**  
     * Enters the specified room and prints the description  
     */  
    private void enterRoom(Room nextRoom)  
    {  
        currentRoom = nextRoom;  
        gui.println(currentRoom.getLongDescription());  
          
          
        if(currentRoom.getImageName() != null)  
        {  
            gui.showImage(currentRoom.getImageName());  
        }  
    }  
      
    /**  
     * Move the player to a new Room.  
     *  
     * @param pRoom the room to go  
     */  
    private void movePlayer(final Room pRoom)  
    {  
        this.choc.setCurrentRoom(pRoom);  
        gui.println(this.choc.getCurrentRoom().getLongDescription());  
          
        if(this.choc.getCurrentRoom().getImageName() != null)  
        {  
          gui.showImage(this.choc.getCurrentRoom().getImageName());  
        }  
    }  
          
    private void endGame()  
    {  
        gui.println("Merci d'avoir jouer. Aurevoir");  
        gui.enable(false);  
    }  

    private void look()  
    {  
        gui.println(currentRoom.getLongDescription());  
    }  
      
    private void energie()  
    {  
        gui.println("Tu viens de boire une boisson energisante! Choc est en pleine forme!");  
    }  
      

   
      /**   
     * Try to take an item from the current room. If the item is there,  
     * pick it up, if not print an error message.  
     */  
    private void prendre(Command command)   
    {  
        if(!command.hasSecondWord()) {  
            // if there is no second word, we don't know what to take...  
            gui.println("Que veux tu prendre?");  
            return;  
        }  

        String vItemName = command.getSecondWord();  
        Item vitem = this.choc.getCurrentRoom().getItems().getItem(vItemName);  
        //choc.pickUpItem(vitemName);  
          
        if(vitem == null) {  
            gui.println(vItemName+ " est introuvable");  
        }   
         
        //         int vFuturPoids = this.choc.getItems().getTotalPoids() + vitem.getItemPoids();  
        //        if (vFuturPoids > this.choc.getMaxPoids())  
        //        {  
        //            this.gui.println( " Tu ne peux pas prendre d'item supplémentaire");  
        //            return;  
        //         }  
          
        this.choc.getItems().addItem(vItemName, vitem);  
        this.choc.getCurrentRoom().getItems().remove(vItemName);  
        this.gui.println("Tu as pris " + vItemName);  
      
    }  
      
      
    //private void teleportation (Command command){  
     //   if (choc.getCurrentRoom() == teleportation) {      
      //  Room nextRoom = currentRoom;  
      //  enterRoom(nextRoom);  
          
      //  choc.getCurrentRoom();  
      
     // }  
   // }  
      
    /**   
     * Drops an item into the current room. If the player carries the item  
     * drop it, if not print an error message.  
     */  
    private void poser(Command command)   
    {  
        if(!command.hasSecondWord()) {  
            // if there is no second word, we don't know what to drop...  
            gui.println("Que veux tu poser?");  
            return;  
        }  

        String vitemName = command.getSecondWord();  
        Item vitem = this.choc.getItems().getItem( vitemName);  
          
        if(vitem == null) {  
            gui.println("Tu ne portes pas les items suivants: " + vitemName);  
            return;  
        }   
          
        this.choc.getCurrentRoom().getItems().addItem(vitemName, vitem);  
        this.choc.getItems().remove(vitemName);  
        this.gui.println("Tu viens de poser " + vitemName);  
    }  
      
    /**  
     * Prints out the items that the player is currently carrying.  
     */  
    private void printItems() {  
        gui.println(choc.getItemsString());     
    }  
      
    
      
    /**   
     * "Quit" was entered. Check the rest of the command to see  
     * whether we really quit the game.  
     * @return true, if this command quits the game, false otherwise.  
     */  
    private boolean quit(Command command)   
    {  
        if(command.hasSecondWord()) {  
            gui.println("Quitter quoi?");  
            return false;  
        }  
        else {  
            return true;  // signal that we want to quit  
        }  

    }  
      
      
    ///private void goRandomRoom(){  
       // int nbRoom = rooms.size();  
          
       // int random = (int)(Math.random() * (nbRoom));  
          
       // System.out.println("\n ------- Aaaaah !! you're sucked into a black hole -------\n");  
          
       // currentRoom = (Room) rooms.get(random);  
       // System.out.println(currentRoom.getLongDescription());                
          
    //}  
      
      /**  
     * Gets the list room.  
     *  
     * @return the list room  
     */  
    public static HashMap <String,Room> getListRoom ()  
    {  
        return GameEngine.aListRoom;   
    }  
      
     //     public void alea(Command command)  
     //  {  
     //        if(!command.hasSecondWord()) {  
                // if there is no second word, we don't know what to take...  
      //         ((TransporterRoom) choc.getCurrentRoom()).unsetAleaString();  
      //          return;  
      //      }  
              
       //     String aleaString = command.getSecondWord();  
       //     ((TransporterRoom) player.getCurrentRoom()).setAleaString(aleaString);  
       // }  
          
}  
 


1 réponse

KX Messages postés 16760 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 12 février 2025 3 020
8 mai 2013 à 21:45
CommandWord est un enum ?

Ta méthode switch (vCommandWord) renvoie un NullPointerException parce que ton instruction vCommand.getCommandWord() renvoie null, ce qui n'est pas une valeur enum autorisée pour un switch. Tu dois tester le cas où ça vaut null avant de faire ton switch.
0
Oui CommandWords est un enum

Je comprend pas, pourtant j'ai mis nulle part que vCommand vallait null ?

quand tu dis tester le cas où ça veut null, je doit faire comment ?

merci beaucoup beaucoup en tout cas
0
KX Messages postés 16760 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 12 février 2025 3 020
8 mai 2013 à 23:25
Je n'ai pas dit que vCommand valait null, mais c'est le résultat de "vCommand.getCommandWord()" qui vaut null, c'est du moins comme ça que j'interprète le NullPointerException sur ton switch...

Tester le cas où ça vaut null ça veut dire faire comme ça (par exemple)

if (vCommandWord==null)
{
    ...
}
else
{
    switch (vCommandWord)
    {
        ...
    }
}
0
aaaaaaaaah ça marche! Merci beaucoup !
0