Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 5 of 5

Thread: "Exception in thread "main" java.lang.NullPointerException" help?

  1. #1
    Junior Member
    Join Date
    Feb 2014
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default "Exception in thread "main" java.lang.NullPointerException" help?

    As the title describes, I get an error when I run the "Memory" file. When I compile it nothing's wrong, but when I run the file it starts to complain. To be more specific it says:

    Exception in thread "main" java.lang.NullPointerException
    at Memory.<init>(Memory.java:49)
    at Memory.newGame(Memory.java:353)
    at Memory.main(Memory.java:348)
    Any ideas on what may be wrong and how I can fix it?

    1. Card

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
     
    public class Card extends JButton {
       // instance variable
       private Icon icon;
       private Status status;
     
       // constructors 
       public Card(Icon a) {
          icon = a;
          setStatus(Status.MISSING); // sets the cards background and icon 
       }
     
       public Card(Icon a, Status status) {
          icon = a;
          setStatus(status); 
       }
     
       // enum
       public enum Status  {
          HIDDEN, VISIBLE, MISSING;
       }
     
       // methods
       public void setStatus (Status status) {
          this.status = status;
          if (this.status == Status.HIDDEN) { 
             this.setBackground(Color.blue);
             this.setIcon(null);
          } else { 
             if (this.status == Status.MISSING) { 
                this.setBackground(Color.white);
                this.setIcon(null);
             } else {
                if (this.status == Status.VISIBLE) { 
                   this.setBackground(Color.blue);
                   this.setIcon(icon);
                }
               }
            } 
       }
     
       public Status getStatus () {
          return this.status; 
       } 
     
       public Card copy () {
          return new Card (icon, this.status);
       }
     
       public boolean equalIcon (Card a) {
          return icon == a.icon;
       }      
     
    }

    2. Tools
    public class Tools {
    	// adds object in an array in a random order
    	public static void randomOrder(Object[] a) {
    		Object[] temp = new Object[a.length];
    		for (int i = 0; i < a.length; i=i+1) {
    			temp[i] = a[i];
    			a[i] = null;
    		}
     
     
    		int i = 0;
    		while (i < a.length) {
     
    			int f = (int) (Math.random()*a.length);
    			if (a[f] == null) {
    				a[f] = temp[i];
    				i=i+1;
    			}
    		}
     
    	}
     
    }

    3. Player

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Font;
     
    import javax.swing.BorderFactory;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.border.EmptyBorder;
     
     
    // the class Player used to describe the game's players
    public class Player extends JPanel {
     
    	private String name;
    	private int points;
    	private boolean active;
    	private JLabel nameLabel;
    	private JLabel pointsLabel;
    	private Font nameFont, pointsFont;
     
    	// constructor for player - recieves names, adds labels and initializes points and activities
    	public Player(String name) {
     
    		setLayout(new BorderLayout());
     
    		nameFont = new Font("Default", Font.BOLD, 10);
    		pointsFont = new Font("Default", Font.BOLD, 25);
     
    		this.name = name;
    		nameLabel = new JLabel(name, JLabel.CENTER);
    		nameLabel.setFont(nameFont);
     
    		points = 0;
    		pointsLabel = new JLabel(((Integer) points).toString(), JLabel.CENTER);
    		pointsLabel.setFont(pointsFont);
     
    		active = false;
     
    		add(nameLabel, BorderLayout.NORTH);
    		add(pointsLabel, BorderLayout.CENTER);
     
    		setBackground(Color.GRAY);
    		setBorder(new EmptyBorder(10,10,10,10));
    		setBorder(BorderFactory.createLineBorder(Color.BLACK));		
    	}
     
    	// adds 1 to points and edits the text on its label
    	public void addPoint() {
    		points=points+1;
    		pointsLabel.setText(((Integer) points).toString());
    	}
     
    	// returns the player's state
    	public boolean getActivity() {
    		return active;
    	}
     
    	// changes a player's state to the parameter and then changes the background
    	public void setActivity(boolean t) {
    		active = t;
    		if (t) {
    			setBackground(Color.YELLOW);
    		}
     
    		else {
    			setBackground(Color.GRAY);
    		}
    	}
     
    	// returns the player's name
    	public String getName() {
    		return name;
    	}
     
    	// returns the player's points
       	public int getPoints() {
    		return points;
    	}
     
    	// resets the player's points
    	public void resetPoints() {
    		points = 0;
    		pointsLabel.setText("  "+((Integer) points).toString());
    	}
    }

    4. The memory game
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.File;
    import javax.swing.BoxLayout;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.Timer;
     
    public class Memory extends JFrame implements ActionListener {
    	private Timer t;
     
    	// game's size is size * size
    	private int size;
     
    	// all available cards
    	private Card[] allCards;
     
    	// all active cards
       private Card[] playCards; 
     
    	// panels for cards and playerspanel
    	private JPanel cardsPanel, playersPanel;
     
    	// array holding the players
       private Player[] players;
     
    	// menubars
    	private JMenuBar menuBar;
    	private JMenu menuGame, menuSettings;
    	private JMenuItem nytt, sluta, spelareSetting, sizeSetting;
     
    	// constructors for memory where the headframe and the menu initialise withe the available cards
    	public Memory() {
    		t = new Timer(1200, this);
     
    		setTitle("Memory");
     
    		// adds all the cards to mypictures in allCards
    		File folder = new File("mypictures");
    		File[] pictures = folder.listFiles();
     
    		allCards = new Card[pictures.length];
     
    		for(int i = 0; i < pictures.length; i=i+1) {
    			ImageIcon icon = new ImageIcon(pictures[i].getPath());
    			allCards[i] = new Card(icon, Card.Status.HIDDEN);
    		}
     
    		// placing all the graphic components
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		setLayout(new BorderLayout());
     
    		menuBar = new JMenuBar();
    		setJMenuBar(menuBar);
     
    		menuGame = new JMenu("Game");
    		menuSettings = new JMenu("Settings");
     
    		menuBar.add(menuGame);
    		menuBar.add(menuSettings);
     
    		nytt = new JMenuItem("New");
    		menuGame.add(nytt);
     
    		sluta = new JMenuItem("Stop");
    		menuGame.add(sluta);
     
    		spelareSetting = new JMenuItem("Players");
    		menuSettings.add(spelareSetting);
     
    		sizeSetting = new JMenuItem("Size");
    		menuSettings.add(sizeSetting);
     
    		nytt.addActionListener(this);
    		sluta.addActionListener(this);
    		sizeSetting.addActionListener(this);
    		spelareSetting.addActionListener(this);
     
    		pack();
    		setSize(600, 600);
    		setVisible(true);
     
    		// sets players and game size
    		setSize();
    		setPlayers();
     
    	}
     
    	// opens a dialogue where you get to decide new game size
    	public int newGameSize() {
    		boolean exit = false;
    		int sizet = 0;
     
    		while (!exit) {
    			sizet = Integer.parseInt(JOptionPane.showInputDialog(null, 
    														"Difficulty? 4 or 6."));
    			if (4 == sizet || sizet == 6) {
    				exit = true;
    			}
    			else {
    				JOptionPane.showMessageDialog(null, "error");
    			}
    		}
    		return sizet;
     
    	}
     
    	// opens a dialogue where you get to decide the number of players
    	public Player[] nrOfPlayers(){
     
    		boolean exit = false;
    		int sizet = 0;
     
    		while (!exit) {
    			sizet = Integer.parseInt(JOptionPane.showInputDialog(null,
    												"Number of Players? 1 - 4"));
    			if (1 <= sizet && sizet <= 4) {
    				exit = true;
    			}
    			else {
    				JOptionPane.showMessageDialog(null, "error");
    			}
    		}
     
    		players = new Player[sizet];
     
    		for(int i = 0; i < sizet; i=i+1){
    			players[i] = new Player(JOptionPane.showInputDialog(null, "Name?"));
    		}
     
    		return players;
    	}
     
    	// sets new game size and places out all the cards in random order
    	public void setSize() {
    		size = newGameSize();
     
    		if (cardsPanel != null) {
    			cardsPanel.setVisible(false);
    		}
     
    		Tools.randomOrder(allCards);
    		playCards = new Card[size*size];
     
    		for (int i = 0; i < ((size*size)); i+=2) {
    			playCards[i] = allCards[i];
    			playCards[i+1] = allCards[i].copy();
    		}
     
    		Tools.randomOrder(playCards);
     
    		cardsPanel = new JPanel();
    		cardsPanel.setLayout(new GridLayout(size,size));
     
     
    		for(int i = 0; i < playCards.length; i=i+1) {
    			cardsPanel.add(playCards[i]);
    			playCards[i].addActionListener(this);
    		}
     
    		add(cardsPanel, BorderLayout.CENTER);
    		setVisible(true);
    	}
     
    	// sets number of players and places out labels for each player
       	public void setPlayers() {
    		players = nrOfPlayers();
     
    		if (playersPanel != null) {
    			playersPanel.setVisible(false);
    		}
     
    		players[0].setActivity(true);
     
    		playersPanel = new JPanel();
    		playersPanel.setLayout(new BoxLayout(playersPanel, 
    												BoxLayout.Y_AXIS));
    		playersPanel.setSize(50, 600);
     
    		for(int i = 0; i < players.length; i=i+1) {
    			playersPanel.add(players[i]);
    		}
     
    		add(playersPanel, BorderLayout.WEST);
     
    		setVisible(true);
    	}
     
    	// listener, listens for every action performed
    	public void actionPerformed(ActionEvent e){
     
    		// when the timer isn't running
    		if (!t.isRunning()) {		
    			// pressing the button "new"
    			if ("New".equals(e.getActionCommand())) {
    				dispose();
    				newGame();
    			}
     
    			// pressing the button "stop"
             else if ("Stop".equals(e.getActionCommand())) {
    				System.exit(0);
    			}
     
    			// pressing the button "size"
    			else if ("Size".equals(e.getActionCommand())) {
     
    				for(int i = 0; i < players.length; i=i+1) {
    					players[i].resetPoints();
    					players[i].setActivity(false);
    				}
     
    				for(int i = 0; i < playCards.length; i=i+1) {
    					playCards[i].setStatus(Card.Status.HIDDEN);
    				}
     
    				players[0].setActivity(true);
     
    				setSize();
     
    				setVisible(false);
    				setVisible(true);
    			}
     
    			// pressing the button "players"
             	else if ("Players".equals(e.getActionCommand())) {
     
    				for(int i = 0; i < playCards.length; i=i+1) {
    					playCards[i].setStatus(Card.Status.HIDDEN);
    				}
     
    				setPlayers();
    				setVisible(false);
    				setVisible(true);
    			}
     
    			// if you're done initializing players and cards
    			else if (!(((Card) e.getSource()).getStatus() 
    					                      == Card.Status.MISSING)) {
     
    				int temp = 0;
     
    				((Card) e.getSource()).setStatus(Card.Status.VISIBLE);
     
    				for(int i = 0; i < size*size; i=i+1) {
    					if (playCards[i].getStatus() == Card.Status.VISIBLE) {
    						temp++;
    					}	
    				}
     
    				// if there's more than 1 visible card the timer will set for an intervall of 1.5 seconds
    				if (temp > 1){			
    					t.start();								
    				}					
    			}
    		}
     
    		// if actionevent is timer t
    		else if (e.getSource() == t) {
     
    			t.stop();
     
    			Card[] tempCard = new Card[2];
    			int temp = 0;
    			int f = 0;
     
    			for(int i = 0; i < size*size; i=i+1){
     
    				// copies visible cards
    				if (playCards[i].getStatus() == Card.Status.VISIBLE) {
    					tempCard[temp] = playCards[i];
    					temp=temp+1;
    				}
    				// the variable f is added to decide when the game is over
    				if (playCards[i].getStatus() == Card.Status.MISSING) {
    					f=f+1;
    				}	
    			}
     
    			// if the two visible cards are equal
    			if (tempCard[0].equalIcon(tempCard[1])) {
     
    				tempCard[0].setStatus(Card.Status.MISSING);
    				tempCard[1].setStatus(Card.Status.MISSING);
     
    				// adds 1 point to the player that is active
    				for(int i = 0; i < players.length; i=i+1) {
     
    					if (players[i].getActivity()) {
     
    						players[i].addPoint();
     
    					}
    				}
    			}
     
    			// decides who's turn it is
    			else {
     
    				tempCard[0].setStatus(Card.Status.HIDDEN);
    				tempCard[1].setStatus(Card.Status.HIDDEN);
     
    				for(int i = 0; i < players.length; i=i+1) {
     
    					if (players[i].getActivity()) {
     
    						players[i].setActivity(false);
     
    						if (i == players.length-1) {
    							players[0].setActivity(true);
    							break;
    						}
    						else {
    							players[i+1].setActivity(true);
    							break;
    						}
    					}
    				}
    			}
     
    			// decides who the winner is
    			if(f >= size*size-2) {
    				Player winner = players[0];
     
    				for(int i = 1; i < players.length; i=i+1) {
    					if (winner.getPoints() < players[i].getPoints()) {
    						winner = players[i];
    					}
    				}
     
    				JOptionPane.showMessageDialog(null, winner.getName() + " won");
     
    				dispose();
    				newGame();
    			}	
    		}
    	}
     
     
    	public static void main(String[] args) {
    		newGame();
    	}
     
    	// Creates a new Memory
    	public static void newGame() {
    		new Memory();
    	}
    }


  2. #2
    Senior Member PhHein's Avatar
    Join Date
    Mar 2013
    Location
    Germany
    Posts
    609
    My Mood
    Sleepy
    Thanks
    10
    Thanked 93 Times in 86 Posts

    Default Re: "Exception in thread "main" java.lang.NullPointerException" help?

    Something in line 49 of your Memory.java file is null.

  3. #3
    Member andbin's Avatar
    Join Date
    Dec 2013
    Location
    Italy
    Posts
    443
    Thanks
    4
    Thanked 122 Times in 114 Posts

    Default Re: "Exception in thread "main" java.lang.NullPointerException" help?

    Quote Originally Posted by redstripes View Post
    Any ideas on what may be wrong and how I can fix it?
    Line 49 is this:

    allCards = new Card[pictures.length];

    pictures may be null, it happens on I/O error or more typically if the File on which you invoke listFiles() is not a directory or doesn't exist.
    Andrea, www.andbin.netSCJP 5 (91%) – SCWCD 5 (94%)

    Useful links for Java beginnersMy new project Java Examples on Google Code

  4. #4
    Junior Member
    Join Date
    Feb 2014
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: "Exception in thread "main" java.lang.NullPointerException" help?

    I still don't get how I can fix the problem?

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: "Exception in thread "main" java.lang.NullPointerException" help?

    First you need to find the variable with the null value. Add a println() statement that prints out the value of all the variables on line 49.
    When you know what variable, then work of finding why it does not have a valid value.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Replies: 2
    Last Post: June 22nd, 2013, 10:30 AM
  2. Replies: 1
    Last Post: April 7th, 2013, 03:40 PM
  3. Exception in thread "main" java.lang.NullPointerException problem.......
    By Adam802 in forum What's Wrong With My Code?
    Replies: 4
    Last Post: September 20th, 2012, 02:23 AM
  4. Replies: 3
    Last Post: December 7th, 2011, 02:03 AM
  5. Replies: 7
    Last Post: August 13th, 2011, 01:22 AM