i read this on the net. and i cant understand why i have this mistake?

Thrown when an application attempts to use null in a case where an object is required. These include:

* Calling the instance method of a null object.
* Accessing or modifying the field of a null object.
* Taking the length of null as if it were an array.
* Accessing or modifying the slots of null as if it were an array.
* Throwing null as if it were a Throwable value.

Applications should throw instances of this class to indicate other illegal uses of the null object.

i think the problem is here:

if(pieces[rowStart][columnStart]!=null && pieces[rowStart][columnStart].isMoveValid(pieces, columnStart,rowStart,columnEnd,rowEnd) &&  nonCollision){                

  System.out.println("  "+ columnStart+"  "+rowStart+"  "+columnEnd+"  "+rowEnd);	
				         		       
	pieces[rowEnd][columnEnd]=pieces[rowStart][columnStart];
                                                               
				         		    }
				else{
				         moveValid=false;	
System.out.println("Sorry, that piece cant make that move, try again");
				         		    }

might it be because i try to manipulate the array in that way (piecies)? and then send to print..
i tried to run my code. it works, but when it comes back , second type through the loop , it gives me that mistake.
it says 2 lines.
chessInterface.print
chessInterface.main


here is the code i am trying to run. all the methods work the first time. it prints me the screen and asks the questions then coverts them to numbers

public static void main(String[] arg){
	   	   	   
	   Console console=System.console();
	  	   
		   

	   String chessPiece="";
	   int rowStart = 0;
	   int number=0;  
	 
	   char firstLetter=' ';
	   char secondLetter=' ';
	   boolean pieceDevour=false;
	   int rowEnd=0;
	  

	   ChessPiece[][]pieces =new ChessPiece[9][9];
	   boolean nonCollision=false;
	   boolean secondLetterNotNull=false;   
	   boolean checkMate=false;
	   boolean checkSafe=false;
	   boolean promotion = false;
	   boolean validPromotion=false;
	   boolean moveValid=false;
	   boolean valid1=false;
           boolean valid2 = false;
	   int columnStart = 0;
	   int columnEnd=0;	
			
			   pieces[2][1]=new Pawn("Bpn1");
			   pieces[2][2]=new Pawn("Bpn2");
			   pieces[2][3]=new Pawn("Bpn3");
			   pieces[2][4]=new Pawn("Bpn4");
			   pieces[2][5]=new Pawn("Bpn5");
			   pieces[2][6]=new Pawn("Bpn6");
			   pieces[2][7]=new Pawn("Bpn7");
			   pieces[2][8]=new Pawn("Bpn8");
			   					  
			      pieces [1][1]=new Rook("BR1");
				  pieces [1][2]=new Knight("BN1");
				  pieces [1][3]=new Bishop("BB1");
				  pieces [1][4]=new King("BKing");
				  pieces [1][5]=new Queen("BQueen");;
				  pieces [1][6]=new Bishop("BB2");
				  pieces [1][7]=new Knight("BN2");
				  pieces [1][8]=new Rook("BR2");		  
		  
				   pieces[7][1]=new Pawn("Wpn1");
				   pieces[7][2]=new Pawn("Wpn2");
				   pieces[7][3]=new Pawn("Bpn3");
				   pieces[7][4]=new Pawn("Wpn4");
				   pieces[7][5]=new Pawn("Wpn5");
				   pieces[7][6]=new Pawn("Wpn6");
				   pieces[7][7]=new Pawn("Wpn7");
				   pieces[7][8]=new Pawn("Wpn8");
				   	   	  
				      pieces [8][1]=new Rook("WR1");
					  pieces [8][2]=new Knight("WN1");
					  pieces [8][3]=new Bishop("WB1");
					  pieces [8][4]=new King("WKing");
					  pieces [8][5]=new Queen("WQueen");;
					  pieces [8][6]=new Bishop("WB2");
					  pieces [8][7]=new Knight("WN2");
					  pieces [8][8]=new Rook("WR2");
					  
					  
			          
			         

			        	 
			        

	
            do{

            	print(pieces);


		               			         					  
				         					
				         							
				         						       System.out.println("what piece do you want to move?");  
				         						       chessPiece=console.readLine();	
				         						       
				         						       System.out.println("where is the piece located?(type row number)");
				         							   rowStart=Integer.parseInt(console.readLine());
				         							   System.out.println("where is the piece located?(type column letter)");
				         						    	 String columnStartC=console.readLine();
				         							 
				         						       
				         						       System.out.println("where do you want to move it to?(type row number)");
				         							   rowEnd=Integer.parseInt(console.readLine());
				         							   System.out.println("where do you want to move it to?(type column letter)");
				         							   String columnEndC=console.readLine();
				         							   
				         							 
				         							   	  	valid1=true;
                                                                                                              valid2=true;
				         							 
													switch(columnStartC.charAt(0))
			         									{
			         										case 'a':  columnStart=1; break;
			         										case 'b':  columnStart=2; break;
			         										case 'c':  columnStart=3; break;
			         										case 'd':  columnStart=4; break;
			         										case 'e':  columnStart=5; break;
			         										case 'f':  columnStart=6; break;
			         										case 'g':  columnStart=7; break;
			         										case 'h':  columnStart=8; break;
			         										default: valid1=false; break;
			         											
			         									} 
			         									 
				         									switch(columnEndC.charAt(0))
				         									{
				         										case 'a':  columnEnd=1; break;
				         										case 'b':  columnEnd=2; break;
				         										case 'c':  columnEnd=3; break;
				         										case 'd':  columnEnd=4; break;
				         										case 'e':  columnEnd=5; break;
				         										case 'f':  columnEnd=6; break;
				         										case 'g':  columnEnd=7; break;
				         										case 'h':  columnEnd=8; break;
				         										default: valid2=false; break;
				         											
				         									} 
                                                           
				         									 if(valid2==false && valid1==false){
				         									 System.out.println("Column doesnt exist , please try again");
				         									 }
                                                                                                                  
				         									  
                                                                                                                      
				         						                         

                                                          
				         						
				         						
				         		
				         				
				         				 
				         				   firstLetter=pieces[rowStart][columnStart].FindPiece(chessPiece).charAt(0); 
				         				   if(pieces[rowEnd][columnEnd]!=null){					   
				         				   secondLetterNotNull=true;
				         				   secondLetter=pieces[rowEnd][columnEnd].FindPiece(chessPiece).charAt(0);
				         				   }
				         				   else{
				         					   secondLetterNotNull=false;
				         				   }


				         				   
				                                       if(secondLetter!=firstLetter && secondLetterNotNull==true){
				                         	       pieceDevour=true;               	 
				                                       }
				                         	           else
				                         	       {
				         		        	    pieceDevour=false;
				                         	       }
				                            
				         				  
				                            if(pieces[rowStart][columnStart].piecesCollision(pieces,rowStart,columnStart ,columnEnd,rowEnd ) | pieceDevour==true){ 
				                         	   nonCollision=true;
				                            }
				                            else{
				                              nonCollision=false;
				                         	   System.out.println("Sorry, your move cant collide with another piece, try again");
				                            }

				         			  
				         			 
				         		    if(pieces[rowStart][columnStart]!=null && pieces[rowStart][columnStart].isMoveValid(pieces, columnStart,rowStart,columnEnd,rowEnd) &&  

nonCollision){                                                  System.out.println("  "+ columnStart+"  "+rowStart+"  "+columnEnd+"  "+rowEnd);	
				         		       
				         			pieces[rowEnd][columnEnd]=pieces[rowStart][columnStart]; // is this line causes the problem?
                                                                  pieces[rowStart][columnStart]=null;   
				         		    }
				         		    else{
				         		    	moveValid=false;
				         		    	System.out.println("Sorry, that piece cant make that move, try again");
				         		    }
				         		    
				         		    	System.out.println("  "+ columnStart+"  "+rowStart+"  "+columnEnd+"  "+rowEnd);	
				         		    
				         		    
				         		    
				         		   
				         		    
				         		
				         		    	
				         		    }while(moveValid!=true);
                                                        
                                                 
				         		  
				         	
				         		
			 }

second method outside the main class, simply prints the board. 1st time it prints with, no problems.

public static void print(ChessPiece[][] pieces){

        	  String[][] array=new String[9][9];
		        String nullSquare="| Null |";
  			
      		for (int a = 0; a <pieces.length; a++) {
      			
      			for (int b = 0; b < pieces[a].length; b++){
      			if(pieces [a][b]!=null){
      			array[a][b]=pieces [9-a][b].print();					
      			}
      				else{
      				
      			 array[a][b]=nullSquare;		
      				
      			}
      			
      		 }
      		}
      		  

      	String rows=" abcdefgh";
      	int num1=9;

      		for (int i = 0; i < array.length; i++) {
      	
      			
      		for (int j = 0; j < array[i].length; j++) {
      			if(i==0){
      			System.out.print("   "+rows.charAt(j)+"    ");
      			}
      			else{
      				if(i>0)
      			System.out.print(array[i][j]);
      			}
      		}	
      		if(i==0)
      		System.out.println();
              if(i>0)
      		System.out.println(num1-i);
      		}				 
    


      }

board output is like this:

a       b       c       d       e       f       g       h    
|Wrook||Wknight||WBishop||WKing||WQueen||WBishop||Wknight||Wrook|8
| Wpn1 || Wpn2 || Bpn3 || Wpn4 || Wpn5 || Wpn6 || Wpn7 || Wpn8 |7
| Null || Null || Null || Null || Null || Null || Null || Null |6
| Null || Null || Null || Null || Null || Null || Null || Null |5
| Null || Null || Null || Null || Null || Null || Null || Null |4
| Null || Null || Null || Null || Null || Null || Null || Null |3
| Bpn1 || Bpn2 || Bpn3 || Bpn4 || Bpn5 || Bpn6 || Bpn7 || Bpn8 |2
|Brook||Bknight||BBishop||BKing||BQueen||BBishop||Bknight||Brook|1

although the array has got [0] column, where there is only null
but i never refer to 0. my object array starts from 1

Recommended Answers

All 42 Replies

You stack trace will indicate the exact line that the error is occurring on.

Please copy and paste here the full text of the error message if you need help understanding what it says.

Exception in the thread main java.lang.NullPointerException

at ChessInterface.print(ChessInterface.java: 212 )
at ChessInterface.main(ChessInterface.java: 80)

i wonder why and where the mistake is?
the loop goes well, the first time around. but the second one..no


ismoveValid could be doing the mistake when i do this swap
pieces[rowEnd][columnEnd]=pieces[rowStart][columnStart];
then i put, start position equals to null. cause the start position should empty itself automatically

Please copy and paste here the full text of the error message. Do NOT edit the stackTrace printout. Show the whole thing.

where the mistake is

The error message has your source code line number where the error occured
ChessInterface.java: 212 ) <<<<<< line 212

Norm1.
notice this. the second time it tries to go in a loop , it gives me the exceptions.
did i mismanage my array. what do i need to add to prevent this?

int z=8;
int b=0;	        

	
            while(b<z){ // it should go 8 times through the loop. on the second time i get the exception. all my methods work, apart from the end

            	print(pieces);

		               			         					  
				         					
				         							
				         						       System.out.println("what piece do you want to move?");  
				         						       chessPiece=console.readLine();	
				         						       
				         						       System.out.println("where is the piece located?(type row number)");
				         							   rowStart=Integer.parseInt(console.readLine());
				         							   System.out.println("where is the piece located?(type column letter)");
				         						    	 String columnStartC=console.readLine();
				         							 
				         						       
				         						       System.out.println("where do you want to move it to?(type row number)");
				         							   rowEnd=Integer.parseInt(console.readLine());
				         							   System.out.println("where do you want to move it to?(type column letter)");
				         							   String columnEndC=console.readLine();
				         							   
				         							 
				         							   	  	valid1=true;
                                                                                                              valid2=true;
				         							 
													switch(columnStartC.charAt(0))
			         									{
			         										case 'a':  columnStart=1; break;
			         										case 'b':  columnStart=2; break;
			         										case 'c':  columnStart=3; break;
			         										case 'd':  columnStart=4; break;
			         										case 'e':  columnStart=5; break;
			         										case 'f':  columnStart=6; break;
			         										case 'g':  columnStart=7; break;
			         										case 'h':  columnStart=8; break;
			         										default: valid1=false; break;
			         											
			         									} 
			         									 
				         									switch(columnEndC.charAt(0))
				         									{
				         										case 'a':  columnEnd=1; break;
				         										case 'b':  columnEnd=2; break;
				         										case 'c':  columnEnd=3; break;
				         										case 'd':  columnEnd=4; break;
				         										case 'e':  columnEnd=5; break;
				         										case 'f':  columnEnd=6; break;
				         										case 'g':  columnEnd=7; break;
				         										case 'h':  columnEnd=8; break;
				         										default: valid2=false; break;
				         											
				         									} 
                                                           
				         									 if(valid2==false && valid1==false){
				         									 System.out.println("Column doesnt exist , please try again");
				         									 }
                                                                                                                  
				         									  
                                                                                                                      
				         						                         

                                                          
				         						
				         						
				         		
				         				
				         				 
				         				   firstLetter=pieces[rowStart][columnStart].FindPiece(chessPiece).charAt(0); 
				         				   if(pieces[rowEnd][columnEnd]!=null){					   
				         				   secondLetterNotNull=true;
				         				   secondLetter=pieces[rowEnd][columnEnd].FindPiece(chessPiece).charAt(0);
				         				   }
				         				   else{
				         					   secondLetterNotNull=false;
				         				   }


				         				   
				                                       if(secondLetter!=firstLetter && secondLetterNotNull==true){
				                         	       pieceDevour=true;               	 
				                                       }
				                         	           else
				                         	       {
				         		        	    pieceDevour=false;
				                         	       }
				                            
				         				  
				                            if(pieces[rowStart][columnStart].piecesCollision(pieces,rowStart,columnStart ,columnEnd,rowEnd ) | pieceDevour==true){ 
				                         	   nonCollision=true;
				                            }
				                            else{
				                              nonCollision=false;
				                         	   System.out.println("Sorry, your move cant collide with another piece, try again");
				                            }

				         			  
				         			 
				         		    if(pieces[rowStart][columnStart]!=null && pieces[rowStart][columnStart].isMoveValid(pieces, columnStart,rowStart,columnEnd,rowEnd) &&   

nonCollision){                                                  System.out.println("true");	
				         		       
				         			pieces[rowEnd][columnEnd]=pieces[rowStart][columnStart];
                                                                 pieces[rowStart][columnStart]=null;  
                                                                  moveValid=true; 
                                                               
				         		    }
				         		    else{
				         		    	moveValid=false;
				         		    	System.out.println("Sorry, that piece cant make that move, try again");
				         		    }
				         		    
				         		    		
				         		    
				         		    
				         		    
				         		   
				         		    b++;
				         		
				         		    	
				         		    }
                                                        
                                                 
				         		  
				         	
				         		
				









         	}

that is in the line
for (int a = 0; a <pieces.length; a++) {
// it is a line for printing the table in the print method.

here is the full method:

public static void print(ChessPiece[][] pieces){

        	  String[][] array=new String[9][9];
		        String nullSquare="| Null |";
  			
      		for (int a = 0; a <pieces.length; a++) {
      			
      			for (int b = 0; b < pieces[a].length; b++){
      			if(pieces [a][b]!=null){
      			array[a][b]=pieces [9-a][b].print();					
      			}
      				else{
      				
      			 array[a][b]=nullSquare;		
      				
      			}

there is another part , but it is irrelevant.


print(pieces); shown also as a mistake.

i copied and posted the mistake as it was written..

the main code sends a new array to the print(). but the pritn method rejects it .
The only time i apply a method to the new array is here

if(pieces [a]!=null){
array[a]=pieces [9-a].print();

The error occurs on line 212, which we can't determine when only portions of the file are shown here, but I would be suspicious of this part

pieces [9-a][b].print()

potentially executing against a null reference.

This could also be problematic if you are using a sparsely populated array

for (int b = 0; b < pieces[a].length; b++){

edit: nt, server double posted my reply

very good point, Ezzaral. very good point


here is my whole

very good point, Ezzaral. very good point


here is my whole main class code:

import java.io.*;
class ChessInterface {


public static void main(String[] arg){
	   	   	   
	   Console console=System.console();
	  	   
		   

	   String chessPiece="";
	   int rowStart = 0;
	   int number=0;  
	 
	   char firstLetter=' ';
	   char secondLetter=' ';
	   boolean pieceDevour=false;
	   int rowEnd=0;
	  

	   ChessPiece[][]pieces =new ChessPiece[9][9];
	   boolean nonCollision=false;
	   boolean secondLetterNotNull=false;   
	   boolean checkMate=false;
	   boolean checkSafe=false;
	   boolean promotion = false;
	   boolean validPromotion=false;
	   boolean moveValid=false;
	   boolean valid1=false;
           boolean valid2 = false;
	   int columnStart = 0;
	   int columnEnd=0;	
			
			   pieces[2][1]=new Pawn("Bpn1");
			   pieces[2][2]=new Pawn("Bpn2");
			   pieces[2][3]=new Pawn("Bpn3");
			   pieces[2][4]=new Pawn("Bpn4");
			   pieces[2][5]=new Pawn("Bpn5");
			   pieces[2][6]=new Pawn("Bpn6");
			   pieces[2][7]=new Pawn("Bpn7");
			   pieces[2][8]=new Pawn("Bpn8");
			   					  
			      pieces [1][1]=new Rook("BR1");
				  pieces [1][2]=new Knight("BN1");
				  pieces [1][3]=new Bishop("BB1");
				  pieces [1][4]=new King("BKing");
				  pieces [1][5]=new Queen("BQueen");;
				  pieces [1][6]=new Bishop("BB2");
				  pieces [1][7]=new Knight("BN2");
				  pieces [1][8]=new Rook("BR2");		  
		  
				   pieces[7][1]=new Pawn("Wpn1");
				   pieces[7][2]=new Pawn("Wpn2");
				   pieces[7][3]=new Pawn("Bpn3");
				   pieces[7][4]=new Pawn("Wpn4");
				   pieces[7][5]=new Pawn("Wpn5");
				   pieces[7][6]=new Pawn("Wpn6");
				   pieces[7][7]=new Pawn("Wpn7");
				   pieces[7][8]=new Pawn("Wpn8");
				   	   	  
				      pieces [8][1]=new Rook("WR1");
					  pieces [8][2]=new Knight("WN1");
					  pieces [8][3]=new Bishop("WB1");
					  pieces [8][4]=new King("WKing");
					  pieces [8][5]=new Queen("WQueen");;
					  pieces [8][6]=new Bishop("WB2");
					  pieces [8][7]=new Knight("WN2");
					  pieces [8][8]=new Rook("WR2");
					  
					  
			          
			         

			        	 
		int z=8;
int b=0;	        

	
            while(b<z){

            	print(pieces);

		               			         					  
				         					
				         							
				         						       System.out.println("what piece do you want to move?");  
				         						       chessPiece=console.readLine();	
				         						       
				         						       System.out.println("where is the piece located?(type row number)");
				         							   rowStart=Integer.parseInt(console.readLine());
				         							   System.out.println("where is the piece located?(type column letter)");
				         						    	 String columnStartC=console.readLine();
				         							 
				         						       
				         						       System.out.println("where do you want to move it to?(type row number)");
				         							   rowEnd=Integer.parseInt(console.readLine());
				         							   System.out.println("where do you want to move it to?(type column letter)");
				         							   String columnEndC=console.readLine();
				         							   
				         							 
				         							   	  	valid1=true;
                                                                                                              valid2=true;
				         							 
													switch(columnStartC.charAt(0))
			         									{
			         										case 'a':  columnStart=1; break;
			         										case 'b':  columnStart=2; break;
			         										case 'c':  columnStart=3; break;
			         										case 'd':  columnStart=4; break;
			         										case 'e':  columnStart=5; break;
			         										case 'f':  columnStart=6; break;
			         										case 'g':  columnStart=7; break;
			         										case 'h':  columnStart=8; break;
			         										default: valid1=false; break;
			         											
			         									} 
			         									 
				         									switch(columnEndC.charAt(0))
				         									{
				         										case 'a':  columnEnd=1; break;
				         										case 'b':  columnEnd=2; break;
				         										case 'c':  columnEnd=3; break;
				         										case 'd':  columnEnd=4; break;
				         										case 'e':  columnEnd=5; break;
				         										case 'f':  columnEnd=6; break;
				         										case 'g':  columnEnd=7; break;
				         										case 'h':  columnEnd=8; break;
				         										default: valid2=false; break;
				         											
				         									} 
                                                           
				         									 if(valid2==false && valid1==false){
				         									 System.out.println("Column doesnt exist , please try again");
				         									 }
                                                                                                                  
				         									  
                                                                                                                      
				         						                         

                                                          
				         						
				         						
				         		
				         				
				         				 
				         				   firstLetter=pieces[rowStart][columnStart].FindPiece(chessPiece).charAt(0); 
				         				   if(pieces[rowEnd][columnEnd]!=null){					   
				         				   secondLetterNotNull=true;
				         				   secondLetter=pieces[rowEnd][columnEnd].FindPiece(chessPiece).charAt(0);
				         				   }
				         				   else{
				         					   secondLetterNotNull=false;
				         				   }


				         				   
				                                       if(secondLetter!=firstLetter && secondLetterNotNull==true){
				                         	       pieceDevour=true;               	 
				                                       }
				                         	           else
				                         	       {
				         		        	    pieceDevour=false;
				                         	       }
				                            
				         				  
				                            if(pieces[rowStart][columnStart].piecesCollision(pieces,rowStart,columnStart ,columnEnd,rowEnd ) | pieceDevour==true){ 
				                         	   nonCollision=true;
				                            }
				                            else{
				                              nonCollision=false;
				                         	   System.out.println("Sorry, your move cant collide with another piece, try again");
				                            }

				         			  
				         			 
				         		    if(pieces[rowStart][columnStart]!=null && pieces[rowStart][columnStart].isMoveValid(pieces, columnStart,rowStart,columnEnd,rowEnd) &&   

nonCollision){                                                  System.out.println("true");	
				         		       
				         			pieces[rowEnd][columnEnd]=pieces[rowStart][columnStart];
                                                                 pieces[rowStart][columnStart]=null;  
                                                                  moveValid=true; 
                                                               
				         		    }
				         		    else{
				         		    	moveValid=false;
				         		    	System.out.println("Sorry, that piece cant make that move, try again");
				         		    }
				         		    
				         		    		
				         		    
				         		    
				         		    
				         		   
				         		    b++;
				         		
				         		    	
				         		    }
                                                        
                                                 
				         		  
				         	
				         		
				









         	}	
		
               public static void print(ChessPiece[][] pieces){
int a=0;
int b=0;
        	  String[][] array=new String[9][9];
		        String nullSquare="| Null |";
  			
      		for (a = 0; a <9; a++) {
      			
      			for (b = 0; b < 9; b++){
      			if(pieces [a][b]!=null){
      			array[a][b]=pieces [9-a][b].print();					
      			}
      				else{
      				
      			 array[a][b]=nullSquare;		
      				
      			}
      			
      		 }
      		}
      		  

      	String rows=" abcdefgh";
      	int num1=9;
           int i=0;
            int j=0;

      		for ( i = 0; i < 9; i++) {
      	
      			
      		for ( j = 1; j < 9; j++) {
      			if(i==0){
      			System.out.print("   "+rows.charAt(j)+"    ");
      			}
      			else{
      				if(i>0)
      			System.out.print(array[i][j]);
      			}
      		}	
      		if(i==0)
      		System.out.println();
              if(i>0)
      		System.out.println(num1-i);
      		}				 
          }


}

it says i have a mistake at 224

it says i have a mistake at 224

the NPE is not on line 224 in the code you just posted. There are no objects used on that line.

Or is there a different "mistake"/error now.

This is almost fun, like playing 20 questions, trying to figure out what the problem is cause it keeps changing form and getting lost and then popping up in another form in another place. Stay tuned. Maybe next there will be something really exciting happening.

commented: That must mean we're making progress :P +8

when i copy and paste, i think it drops a few lines. but it is clearly unhappy with the applying the new array inside the print method.

why does java refect the new array, when it goes inside the print method?

The question has always been the same, how do i prevent the NullPointerException from happening?

how do i prevent the NullPointerException from happening

The basic way to prevent NPE is to make sure all the object references you use are NOT null. Either assign them all some non-null value or if there is a possibility that a reference could be null, test if it is null: if(objRef != null) before using it.

The basic way to prevent NPE is to make sure all the object references you use are NOT null. Either assign them all some non-null value or if there is a possibility that a reference could be null, test if it is null: if(objRef != null) before using it.

Personally I would prefer using assertions for that purpose.

i did test it. if you notice i put a statement saying if(pieces[][]!=null)

but i see what you are saying. i am going to see how much of the code i can convert. may be i will convert that null, to some string value.
String empty
if(pieces==null)
{
pieces[x][y]=empty;
}

but would that prevent null pointer exception from appearing?


here is my print method again:

public static void print(ChessPiece[][] pieces){
int a=0;
int b=0;
        	  String[][] array=new String[9][9];
		        String nullSquare="| Null |";
  			
      		for (a = 0; a <9; a++) {
      			
      			for (b = 0; b < 9; b++){
      			if(pieces [a][b]!=null){// filters the null right here
      			array[a][b]=pieces [9-a][b].print();					
      			}
      				else{
      				
      			 array[a][b]=nullSquare; //if null. it assigns it a string (null String)		
      				
      			}
      			
      		 }
      		}
      		  

      	String rows=" abcdefgh";
      	int num1=9;
           int i=0;
            int j=0;

      		for ( i = 0; i < 9; i++) {
      	
      			
      		for ( j = 1; j < 9; j++) {
      			if(i==0){
      			System.out.print("   "+rows.charAt(j)+"    ");
      			}
      			else{
      				if(i>0)
      			System.out.print(array[i][j]);
      			}
      		}	
      		if(i==0)
      		System.out.println();
              if(i>0)
      		System.out.println(num1-i);
      		}				 
          }

i still dont understand. what is the problem. the method works for the first time and for the second time. it becomes unhappy..why?

What does unhappy mean when talking about computers and programs?

If the data is there the first time and it is not there the second time, then your program is removing/deleting it between the first and second times.

@tux4life

Personally I would prefer using assertions for that purpose.

how do you use an assertion to test if an object is null and change the code path?
What about when a read returns a null? How would you use an assertion with that?

@NormR1:
>>how do you use an assertion to test if an object is null and change the code path?
After looking a bit deeper in the problem I understand why you're replying this. I was actually a little too fast in replying, and suggested something with limited usefulness (in this context). It's better to just stick with the if as you suggested.
>>What about when a read returns a null? How would you use an assertion with that?
Well, technically it is possible, but it is perhaps a little tedious and a bad practice.

thats is true. but the only change that i make the second time. is when i swap the end piece position to the starting position and declare the start position as equal to null.

why would that be a problem?

#
pieces[rowEnd][columnEnd]=pieces[rowStart][columnStart];
#
pieces[rowStart][columnStart]=null;
#
moveValid=true;

thats the only change that is done to the array. there is no other?

what worries me is that once i change those positions it could be that my loop doesnt let the pieces[][] array to remember. may be i didnt wrap it correctly around the code?!?

why would that be a problem?

If you set something to null and later get a NPE, that could be why.

commented: Thanks for helping +0

could you expand? what does it mean get a NPE?
how could i try and change it?

>how could i try and change it?
As already stated, make sure that the reference is not null before you operate on it.

what should it be?
what does it matter if it isnt null?
i already made it a string, if you look carefully at the print method. why wont it process it?

should i make null an object?

pieces[2][1]=new Pawn("Bpn1");
			   pieces[2][2]=new Pawn("Bpn2");
			   pieces[2][3]=new Pawn("Bpn3");
			   pieces[2][4]=new Pawn("Bpn4");
			   pieces[2][5]=new Pawn("Bpn5");
			   pieces[2][6]=new Pawn("Bpn6");
			   pieces[2][7]=new Pawn("Bpn7");
			   pieces[2][8]=new Pawn("Bpn8");
			   					  
			      pieces [1][1]=new Rook("BR1");
				  pieces [1][2]=new Knight("BN1");
				  pieces [1][3]=new Bishop("BB1");
				  pieces [1][4]=new King("BKing");
				  pieces [1][5]=new Queen("BQueen");;
				  pieces [1][6]=new Bishop("BB2");
				  pieces [1][7]=new Knight("BN2");
				  pieces [1][8]=new Rook("BR2");		  
		  
				   pieces[7][1]=new Pawn("Wpn1");
				   pieces[7][2]=new Pawn("Wpn2");
				   pieces[7][3]=new Pawn("Bpn3");
				   pieces[7][4]=new Pawn("Wpn4");
				   pieces[7][5]=new Pawn("Wpn5");
				   pieces[7][6]=new Pawn("Wpn6");
				   pieces[7][7]=new Pawn("Wpn7");
				   pieces[7][8]=new Pawn("Wpn8");
				   	   	  
				      pieces [8][1]=new Rook("WR1");
					  pieces [8][2]=new Knight("WN1");
					  pieces [8][3]=new Bishop("WB1");
					  pieces [8][4]=new King("WKing");
					  pieces [8][5]=new Queen("WQueen");;
					  pieces [8][6]=new Bishop("WB2");
					  pieces [8][7]=new Knight("WN2");
					  pieces [8][8]=new Rook("WR2");

what if from the begining i did soemthing like this

String empty;
 for (int x=0;x<9;x++)
   for(int y=0;y<9;x++)
  if(pieces[][]!=null)
    pieces[][]=empty;

would that change anything? would that solve the problem?

ChessPiece empty=(ChessPiece) new Object();
					  for (int x=0;x<9;x++)
					    for(int y=0;y<9;x++)
					      if(pieces[x][y]!=null){
					     pieces[x][y]=empty;
					   }

would something like that work??!?!!?

unfortunately it doesnt allow me to convert the null , nor to object or ChessPiece Object or String

Try it, it might work.

Member Avatar for coil

If you're not sure if you will get a null string (for example, if you rely on user input, or create the string through conditional statements), you might want to test to make sure the string isn't null. In that case, yes, if(string!=null) works. Otherwise, if you yourself personally create and initialize the string, then careful coding should eliminate the need for such checks.

no.. i checked the whole thing again!!
once it reaches print() the second time, it doesnt want to print .. it is unsatisfied with the first array.

i dont think that print() algorithm is wrong. if it was wrong, it woulndt have given me the board layout from the begining and threw a mistake "nullpointer exception"

what i think is , that the print() , when it gets inside , it doesnt empty its variables.

could i be right. could someone check it?

public static void print(ChessPiece[][] pieces){//  same pieces[][] array gets in here. but one value in the array was misplaced.
null became a new place in the array, and place that used to be a null became ChessPiece object
                  int a=0;
                  int b=0;
                  String nullSquare="| Null |";   
        	  String[][] array=new String[9][9]; // new array is created
		        
  			
      		for (a = 0; a <9; a++) {//loop for rows
      			
      			for (b = 0; b < 9; b++){ //loop for columns
      			if(pieces [a][b]!=null){  // filters the places that arent null
      			array[a][b]=pieces [9-a][b].print(); //applies a method to them.					
      			}
      				else{
      				
      			 array[a][b]=nullSquare;	/null square is replace by a string defined "| null |"
      				
      			}
      			
      		 }
      		}

// the only change that i did to the array was in the isMoveValid, in the main method.

pieces[rowEnd][columnEnd]=pieces[rowStart][columnStart];
pieces[rowStart][columnStart]=null
String rows=" abcdefgh";
      	int num1=9;
           int i=0;
            int j=0;

      		for ( i = 0; i < 9; i++) {
      	
      			
      		for ( j = 1; j < 9; j++) {
      			if(i==0){
      			System.out.print("   "+rows.charAt(j)+"    ");
      			}
      			else{
      				if(i>0)
      			System.out.print(array[i][j]);
      			}
      		}	
      		if(i==0)
      		System.out.println();
              if(i>0)
      		System.out.println(num1-i);
      		}				 
          }

Here you are checking pieces [a][b] for null, but calling print on pieces [9-a][b]

if(pieces [a][b]!=null){
  array[a][b]=pieces [9-a][b].print();                    
}

is this a syntax mistake?

wont if filter the nulls out. and leave me with the objects which i will be able to apply my method to?


why was it that the first array was printed? and there was no problem?

how come the second array passes through my non null condition

public static void print(ChessPiece[][] pieces){
                  int a=0;
                  int b=0;
                  String nullSquare="| Null |";   
        	  String[][] array=new String[9][9];
		      
  			
      		for (a = 0; a <9; a++) {
      			
      			for (b = 0; b < 9; b++){
      			if(pieces [a][b]!=null){
      			
                                   	
                           array[a][b]=pieces[9-a][b].print();
                              }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.