2011-10-03 2 views
1

Je fais un jeu et il me donne un NullPointerException qui je crois signifie la variable ou ce que j'essaye de faire ne renvoie pas une valeur? J'utilise le code ci-dessous:Java Code - NullPointerException

package OurGame; 

import java.awt.Image; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.util.Random; 

import javax.swing.ImageIcon; 
import javax.swing.JPanel; 
import javax.swing.Timer; 

public class Coin extends JPanel implements ActionListener { 
/** 
    * 
    */ 
    private static final long serialVersionUID = 1L; 

Image img; 

int x,y; 
Timer t; 
Random r; 

     public Coin() { 
      x = 50; 
      y = 50; 

      System.out.println("New coin created: " + x + ", " +y); 

      ImageIcon i = new ImageIcon("C:/coin.png"); 
      img = i.getImage(); 
      System.out.println(i); 

      t = new Timer(3000,this); 
      t.start(); 
     } 

     @Override 
     public void actionPerformed(ActionEvent arg0) { 
      move(); 

     } 

     public void move() { 

      setX(r.nextInt(640)); 
      setY(r.nextInt(480)); 


     } 

     public void setX(int xs) { 
      x = xs; 
     } 

     public void setY(int ys) { 
      y = ys; 
     } 
     public Image getImage(){ 
      return img; 
     } 

     public int getX(){ 
      return x; 
     } 

     public int getY() { 
      return y; 
     } 


} 

L'erreur se produit ici:

 setX(r.nextInt(640)); 

La sortie d'erreur complète est ci-dessous:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException 
    at OurGame.Coin.move(Coin.java:46) 
    at OurGame.Coin.actionPerformed(Coin.java:40) 
    at javax.swing.Timer.fireActionPerformed(Unknown Source) 
    at javax.swing.Timer$DoPostEvent.run(Unknown Source) 
    at java.awt.event.InvocationEvent.dispatch(Unknown Source) 
    at java.awt.EventQueue.dispatchEvent(Unknown Source) 
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) 
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) 
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) 
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) 
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) 
    at java.awt.EventDispatchThread.run(Unknown Source) 

Je ne vois aucune raison pour que cela arriver mais peut-être que vous pouvez aider.

Merci.

Répondre

4

Vous devez initialiser la variable r. Consultez les constructeurs pour java.util.Random, par exemple:

Random r = new Random(); 
+0

Ahh ... whoops ^^ Débutant erreur là, merci. –

6

Vous utilisez r sans jamais dire r = new ....

2

r est nulle. Initialisez-le en premier. Mettez ceci dans votre constructeur:

r = new Random();