GIDForums  

Go Back   GIDForums > Computer Programming Forums > Java Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 20-Feb-2009, 15:42
msafi msafi is offline
New Member
 
Join Date: Feb 2009
Posts: 3
msafi is on a distinguished road

NullPointerException in Java


Can somebody please help me figure out why the following code compiles but gives an error message when I try to run it. The txt file "home.txt" that I'm trying to read it into array contains the numbers bellow. The first row is the size of the array (dimension) i.e this is a four row four col. while the subsequent rows are blocked cells i.e {0,1},{1,3} {2,0}and{2,2}.
I'm guessing the array has some null cells but can't figure out cause I have already declared and initialized. Thanks

"home.txt" file
Code:
4 4 0 1 1 3 2 0 2 2

Error message:

Code:
C:\java>javac Game.java C:\java>java Game Please enter the input text file name words.txt Exception in thread "main" java.lang.NullPointerException at Game$Maze.<init>(Game.java:143) at Game.createMaze(Game.java:46) at Game.main(Game.java:21)

JAVA Code:
    
import java.util.Scanner;
import java.io.*;
 
public class Game {
	
 
	private Maze M;
 
 
    public static void main(String[] args) throws FileNotFoundException, IOException {
 
	  System.out.print("Please enter the input text file name " );
	   //Create a Scanner object
	   Scanner scan = new Scanner (System.in);
	   String userInputFile = scan.next().trim();
 
	   //Create a Game object	
	    Game g = new Game();
	    //Call the createMaze method
	    g.createMaze(userInputFile);
 
 
	 //Call the Play Game method
	  if(g.playGame(0,0))
	      System.out.println("Game successfully solved");
 
	 else
 
 
	      System.out.println("No successfull path found");
 
    }
 
 
     public void createMaze(String fileName)throws FileNotFoundException, IOException  {
	String userFileToMethod = fileName;
 
	//Create a file object
	File userFile = new File(userFileToMethod);
 
	//This scanner is used to read from the file
	Scanner readFromFile = new Scanner (userFile);
	int size = readFromFile.nextInt();
                   
	  Maze M = new Maze(size, readFromFile);
 
 
	//print for debbuging code
	//System.out.println("The first integer is " + Row + " "+Col );
 
 
      }
 
 
	boolean playGame(int row, int col)  {
		 boolean blocked = true;
 
	 if(playGame(0,0)) {
 	    M.maze[row][col].visited();//This cell has been visited
 
	    if (row == M.maze.length && col== M.maze[0].length-1)
 
	    blocked = true;
 
	  else {
            blocked = playGame (row,   col+1); //Right
	    if (!blocked)
 		playGame (row + 1, col) ;
	    if (!blocked)
		playGame (row, col - 1);
	    if (!blocked)
		blocked = playGame (row -1,  col);
	   }
 
		if (blocked)
 
	M.maze[row][col].visited();
       }
		
	return blocked;
	
       }
 
    private boolean checkBounds (int row, int col) {
 
	boolean inbounds = false;
 
	if (row >= 0 && row < M.maze.length && col >=0 && col < M.maze[row].length)
 
	if (M.maze[row][col].isBlocked())
 
	inbounds = true;
 
	return inbounds;
 
    }
 
	/////////////////////////////////////////////////////////////////
	//  String Method
	//////////////////////////////////////////////////////////
 
   public String toString () {
 
	  String st1 = "\n";
 
	for (int row = 0;row < M.maze.length; row++) {
 
 
	for (int col = 0;col < M.maze[row].length; col++) 
	st1 +=M.maze[row][col] + " ";   st1 += "n";
	}
		return st1;
   }
 
	////////////////////////////////////////////////////////////////////
	//Maze Class
	////////////////////////////////////////////////////////////////////
    class Maze {
 
	  private Cell[][] maze;
 
 
	Maze(int n, Scanner s) {
 
	  int size1 = n;
	  Scanner inFile = s;
 
	   maze = new Cell[size1][size1];
 
 
		int junk = inFile.nextInt();
 
	
 
 
 
 
 
	    	while (inFile.hasNext() ) {
 	      	  int row = inFile.nextInt();
 	      	  int col = inFile.nextInt();
 	      	  (maze[row][col]).setBlock();//block the cell
 
		   if  (!inFile.hasNext())
                     
 
		(maze[row][col]).isBlocked();
		   
	
                 }
 
 
 
	  //print for debbuging code
	  System.out.println("The first integer is " + size1+ " and "+junk);
 
 
 	}
 
 
	public Cell getCell(int Row, int Col)  {
	int r = Row;
	int c = Col;
 
	return maze[r][c];
 
	}
 
 
   }
	/////////////////////////////////////////////////////////////////////
	//Cell Class
	///////////////////////////////////////////////////////////////////
 
    class Cell { 
 
	 private boolean isBlocked = false;
	 private boolean visited = false;
	 private boolean marked = false;
         int realy = 3;
 
	public boolean isBlocked() {
 
	     return isBlocked;
	}
 
 
	public void setBlock() {
 
	      isBlocked = true;
	}
 
 
	public boolean visited() {
 
	      return visited;
	}
 
 
	public void block() {
 
	     isBlocked = true;
        }
	public boolean marked () {
	      return marked;
	}
	
	
    }
}
Last edited by admin : 21-Feb-2009 at 07:23. Reason: Please insert your example Java codes between [JAVA] and [/JAVA] tags
  #2  
Old 21-Feb-2009, 09:57
TurboPT's Avatar
TurboPT TurboPT is offline
Senior Member
 
Join Date: Feb 2006
Location: Atlanta, GA
Posts: 1,233
TurboPT is a jewel in the roughTurboPT is a jewel in the roughTurboPT is a jewel in the rough

Re: NullPointerException in java


It appears that two mazes are created?
One here:
JAVA Code:
private Maze M;
The second here:
JAVA Code:
Maze M = new Maze(size, readFromFile);
// this one will only be known within the createMaze() function.
Since I'm sure that class-wide variable 'M' is the intent (the first one), so the other statement [inside createMaze()] just simply needs to be:
JAVA Code:
   M = new Maze(size, readFromFile);
=========================
Now to the original problem...
Java is typically very good about pinpointing the problem area, but one needs to understand where it complains to be able to determine the problem...so lets follow the runtime stack-dump that you were given:
Code:
Exception in thread "main" java.lang.NullPointerException at Game$Maze.<init>(Game.java:143) at Game.createMaze(Game.java:46) at Game.main(Game.java:21)
From the bottom->up, this is the 'problem path', so to speak:
File Game.java, line 21 ==> inside main(), statement calling createMaze()
File Game.java, line 46 ==> inside createMaze(), statement calling new Maze()
File Game.java, line 143 ==> <init> [implies the constructor] at this statement, complaining about the null:
JAVA Code:
    (maze[row][col]).setBlock();//block the cell
So, what seems to be causing the problem there?
Even though you have declared a 4x4 array of Cells as:
JAVA Code:
   maze = new Cell[size1][size1];
Those are merely uninitialized Cell references, all null, and hence the complaint when indexing the first set of values from the file: maze[0][1].isBlocked() -- as that is a null pointer!
So to fix that, just after the declaration, the array needs to be populated with Cell objects, like so:
JAVA Code:
for(int x = 0; x < size1; ++x)
{
	for(int y = 0; y < size1; ++y)
	{
		maze[x][y] = new Cell();//the cell
	}
}
That should help the null pointer, but I'll leave you to investigate a problem with the recursion in playGame(). [causes a stack overflow]

Post another reply if you have more questions, or need more help.
__________________
Use the force...read the source!!
WYCIWYG -- what you code is what you get!
  #3  
Old 10-Mar-2009, 12:47
msafi msafi is offline
New Member
 
Join Date: Feb 2009
Posts: 3
msafi is on a distinguished road

Re: NullPointerException in java


Thanks a lot, Thas was the problem. I populated the array and corrected a few thigs

Msafi
 
 

Recent GIDBlogVista ?Widgets? on Windows XP by LocalTech

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
What is the equivalent in Java for a Function or Module in VB pengwinz Java Forum 2 17-May-2007 20:02
To post messages / click Buttons of a Java Jar App using code Jun0 C Programming Language 1 06-Jan-2007 14:44
To post messages / click Buttons of a Java Jar App using code Jun0 Java Forum 0 06-Jan-2007 11:14
Sun Java Wireless Toolkit JdS Java Forum 0 23-Mar-2006 06:16
Scalability in Java and C++ agx Miscellaneous Programming Forum 7 04-Feb-2006 15:35

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 12:21.


vBulletin, Copyright © 2000 - 2010, Jelsoft Enterprises Ltd.