i established an array of objects. i want to user to name a chess piece, the name of the chesspiece then will search the object in the array

package il.co.ChessInterface;
import il.co.Pawn.Pawn;
import il.co.Bishop.*;
import il.co.King.*;
import il.co.Queen.*;
import il.co.Rook.*;
import il.co.Knight.*;

import java.io.Console;


public class ChessInterface {

   public static void main(String[] arg){
	   	   	   
	   Console console=System.console();
	   
	   String chessPiece="";
	   int rowStart = 0;
	   char columnStart = 0;
	   int i;
	   
       System.out.println("what piece do you want to move?");
	   chessPiece=console.readLine();
		
	   System.out.println("where do you want to move it to?(type column letter)");
	   String input=console.readLine(); // the name of the chess piece is entered "e.g. "Bpn1""
	   char columnEnd=input.charAt(0);
	   System.out.println("where do you want to move it to?(type row number)");
	   int rowEnd=Integer.parseInt(console.readLine());
	   
	   
	  
	   
	   ChessPiece pieces[][];
	   pieces =new ChessPiece[7][7];
	   
	   pieces[1][0]=new Pawn("Bpn1");// this should be searched and found.
	   pieces[1][1]=new Pawn("Bpn2");
	   pieces[1][2]=new Pawn("Bpn3");
	   pieces[1][3]=new Pawn("Bpn4");
	   pieces[1][4]=new Pawn("Bpn5");
	   pieces[1][5]=new Pawn("Bpn6");
	   pieces[1][6]=new Pawn("Bpn7");
	   pieces[1][7]=new Pawn("Bpn8");
	   
	
	   

		  
	      pieces [0][0]=new Rook("BR1");
		  pieces [0][1]=new Knight("BN2");
		  pieces [0][2]=new Bishop("BB3");
		  pieces [0][3]=new King("BR4");
		  pieces [0][4]=new Queen("BQ5");;
		  pieces [0][5]=new Bishop("BB6");
		  pieces [0][6]=new Knight("BN7");
		  pieces [0][7]=new Rook("BR8");

could something like that work:

for(Object x:pieces){
			  if(x==chessPiece)
				  
				  System.out.println("__ "+"|");

all the pieces are located in different classes that arent presented here

Try using the equals method instead of the '=='. You need to override that method in your classes.

As it is a two dimensional array, hope following code will work -

for(ChessPiece[] pie : pieces) {
    for(String x : pie) {
        if(x==chessPiece) {
            //other logic
        }
    }
}

I didn't try it, hope it will work.

Comment on your board size:
pieces =new ChessPiece[7][7];
Most boards I've played on have 8 rows and 8 columns.

if(x==chessPiece) {
The == operator checks if the two references point to the same object. It does NOT look at the contents of the objects. To do that you must use a method. See javaAddict's post.

You don't have to override equals(), you can choose any method name that you want. A problem with using the equals() method is that it is used by the Map classes and others for their purposes.
For your case if you only want to know if the piece is a King and not that it is the White King, you should use your own name for the method.

Do you mean like that?

i put the method inside the piece classes (e.g. Pawn, Knight. ..etc)
it should return 2 values. it tells me where the piece is at...
is that correct?

public int FindPiece(String chessPiece){
	if(chessPiece==name)
		return columnStartN;
	    return rowStart;
		
}
if(chessPiece==name)

Do NOT use == when testing if two Strings are equal. Use the equals() method.

chessPiece.equals(name)

thats what i have so far.

System.out.println("what piece do you want to move?");
	   chessPiece=console.readLine();

Get the pieces name (e.g. "Bpn1")

for(int column=0;column<pieces.length;column++)
					  for(int row=0;column<pieces[row].length;row++)
						  if(pieces[row][column].FindPiece(chessPiece).equals(chessPiece))
							  pieces[columnStartN][rowStart]=pieces[row][column];

That is my "Search engine". it should scan through the array and check which Find method in every class/object(inside every place in the multidimensional array) has a chessPiece name that corresponds with the pieces name (this.name..created by the constructor in every piece class)


The pieces class: Pawn class. the method and what it should retrieve.

String chessPiece;
public String FindPiece(String chessPiece){
	if(chessPiece.equals(name))
		chessPiece=name;
	return chessPiece;

is that any good?

Write a small test program with a class containing a String and add several of them to an array and test your technique. It will be easier for us to help you figure out how to use a method for comparing two objects with a small program the compiles and executes.

I don't know the purpose of the FindPiece method. It always returns a String containing the same as the String value as it was passed as an arg???

i have one error only.. i will show you all my code:

package il.co.ChessInterface;
import il.co.Pawn.Pawn;
import il.co.Bishop.*;
import il.co.King.*;
import il.co.Queen.*;
import il.co.Rook.*;
import il.co.Knight.*;

import java.io.Console;


public class ChessInterface {

   public static void main(String[] arg){
	   	   	   
	   Console console=System.console();
	   
	   String chessPiece="";
	   int rowStartN = 0;
	   char columnStart = 0;
	   int i;
	
       System.out.println("what piece do you want to move?");
	   chessPiece=console.readLine();
		
	   System.out.println("where do you want to move it to?(type column letter)");
	   String input=console.readLine();
	   char columnEnd=input.charAt(0);
	   System.out.println("where do you want to move it to?(type row number)");
	   int rowEnd=Integer.parseInt(console.readLine());
	   
	   	  
	  		int columnStartN = 0, columnEndN=0;
			switch(columnStart)
			{
				case 'a':  columnStartN=1; break;
				case 'b':  columnStartN=2; break;
				case 'c':  columnStartN=3; break;
				case 'd':  columnStartN=4; break;
				case 'e':  columnStartN=5; break;
				case 'f':  columnStartN=6; break;
				case 'g':  columnStartN=7; break;
				case 'h':  columnStartN=8; break;
				default: 
					System.out.println("move invalid try again");
			}
			switch(columnEnd)
			{
				case 'a':  columnEndN=1; break;
				case 'b':  columnEndN=2; break;
				case 'c':  columnEndN=3; break;
				case 'd':  columnEndN=4; break;
				case 'e':  columnEndN=5; break;
				case 'f':  columnEndN=6; break;
				case 'g':  columnEndN=7; break;
				case 'h':  columnEndN=8; break;
				default: 
					System.out.println("move invalid try again");
			}
		  
			
		
			   
			   ChessPiece pieces[][];
			   pieces =new ChessPiece[7][7];
			   
			   pieces[1][0]=new Pawn("Bpn1");
			   pieces[1][1]=new Pawn("Bpn2");
			   pieces[1][2]=new Pawn("Bpn3");
			   pieces[1][3]=new Pawn("Bpn4");
			   pieces[1][4]=new Pawn("Bpn5");
			   pieces[1][5]=new Pawn("Bpn6");
			   pieces[1][6]=new Pawn("Bpn7");
			   pieces[1][7]=new Pawn("Bpn8");
			   
			
			   

				  
			      pieces [0][0]=new Rook("BR1");
				  pieces [0][1]=new Knight("BN2");
				  pieces [0][2]=new Bishop("BB3");
				  pieces [0][3]=new King("BR4");
				  pieces [0][4]=new Queen("BQ5");;
				  pieces [0][5]=new Bishop("BB6");
				  pieces [0][6]=new Knight("BN7");
				  pieces [0][7]=new Rook("BR8");
				  
		  

				 
				  {
		
				  for(int column=0;column<pieces.length;column++)
					  for(int row=0;column<pieces[row].length;row++)
						  if(pieces[row][column].FindPiece(chessPiece).equals(chessPiece)){ 

							  pieces[columnStartN][rowStartN]=pieces[row][column];				           
						       columnStartN=column;
					           rowStartN=row;
						  }
	    
		   if(pieces[columnStartN][rowStartN].isMoveValid(columnStartN,rowStartN,columnEnd,rowEnd)){
		    pieces[columnStartN][rowStartN]=null;   
			pieces[columnStartN][rowStartN]=pieces[columnEndN][rowEnd];
		    }
			else
			{
			System.out.println("move invalid, please try to enter another move");			
			}
		   rowStartN=rowEnd;
		   columnStart=columnEnd;
		   	

		   
		   
		   
		   
		   
			  System.out.println("____________________________________________");
			  
			  for(Object x1:pieces){
				  if(pieces==null)
					  
					  System.out.println("__ "+"|");
				  else
					  ((Pawn) x1).print();
					  
			  }
			  System.out.println("____________________________________________");
		  	  	 
	    
	    			
	    //board[1][4] = board[1][2]; // copies existing pawn to new position and...
	     //board[1][2] = null; // removes it from old position 
	    

   }


}
package il.co.Pawn;

import il.co.ChessInterface.ChessPiece;

public class Pawn extends ChessPiece{
int columnEndN;
int rowEnd;
int columnStartN;
int rowStart;
 String name;


        


public Pawn(String name ){
	this.name=name;
}
	
     public  boolean isMoveValid(int columnStartN, int rowStart,int columnEndN, int rowEnd) {
	{

		int deltaX=columnEndN-columnStartN;
		deltaX=deltaX<0?-deltaX:deltaX;
		int deltaY=rowEnd-rowStart;
		deltaY=deltaY<0?-deltaY:deltaY;
		return deltaY==deltaX;


	}

}	


@Override
public void print() {
	// TODO Auto-generated method stub
	System.out.println(name+"|");
}




String chessPiece;
public String FindPiece(String chessPiece){
	if(chessPiece.equals(name))
		chessPiece=name;
	return chessPiece;

	
	    
		
}
}

i have 6 more class pieces and one abstract class..

package il.co.ChessInterface;



abstract public class ChessPiece {
	  
	 abstract public  boolean isMoveValid(int columnStartN, int rowStart, int columnEnd, int rowEnd);
	
	  abstract public void print();

	 abstract public String FindPiece(String chessPiece); 

   	}

i have no error anywhere

i have no error anywhere

Is your problem solved now?

commented: Thanks for helping +0

i am going to ask my teacher tomorrow.
i have to add so many more algorithms to make this chess game work.


The problem is that i dont know java on a high level, so i dont know what short cuts and efficient ways there are to exploit..

so i thought you could give me some suggestions on how to make the pieces move inside the array

suggestions on how to make the pieces move inside the array

A move would involve a from location and a too location.
There could be a method for each type of piece, that when called with a possible move, would return true or false depending on if that move was legal. Considerations would include if the move was legal for the piece, if the path was blocked, if the target square was occupied by a same team piece, if moving exposed the king to check, etc.
If the method said the move was legal, copy the reference to the piece from its current location, set the location where the piece was to "empty" and store reference to the piece in its new location.

should line 65 be:

pieces =new ChessPiece[?][8];

?

There could be a method for each type of piece, that when called with a possible move, would return true or false depending on if that move was legal. Considerations would include if the move was legal for the piece, if the path was blocked, if the target square was occupied by a same team piece, if moving exposed the king to check, etc.

do you think i should put it in the abstract class?
make the same thing as i did with FindPiece method
for(int row;...)
for(int column;...)
pieces[row][column].CheckValidity()
if(found==true)
System.out.println("")
then if the method returned me true the move is valid (e.g. black piece doesnt hit a black piece)

i added this. but this doesnt have a common method in every piece class..

char firstLetter=' ';
				  char secondLetter=' ';
				   firstLetter=pieces[columnStartN][rowStartN].FindPiece(chessPiece).charAt(0); // checks if the first letter is B as in Black (the name of the black pieces begins with B, e.g. Bpn1, black pawn 1)
				   secondLetter=pieces[columnEndN][rowEnd].FindPiece(chessPiece).charAt(0); // checks if the destination position typed by the user (e.g. columnEndN=d, rowEnd=4), has a piece name that also begins with B
                   if(secondLetter==firstLetter) // if both letters are B, it means that a black piece tries to move onto a black  pice
                	   System.out.println("sorry, you cant move onto one of your own pieces");

Norm1, is it possible to write it this way or is there a better way?


here is how my algorithm starting to connect

char firstLetter=' ';
				  char secondLetter=' ';
				  boolean pieceDevour=false;
				   firstLetter=pieces[columnStartN][rowStartN].FindPiece(chessPiece).charAt(0);
				   secondLetter=pieces[columnEndN][rowEnd].FindPiece(chessPiece).charAt(0);
                   if(secondLetter==firstLetter)
                	   pieceDevour=false;
                	   System.out.println("sorry, you cant move onto one of your own pieces");
				  if(firstLetter=='B' & secondLetter=='W')
					  pieceDevour=true;
				  
				  
                   
		   if(pieces[columnStartN][rowStartN].isMoveValid(columnStartN,rowStartN,columnEndN,rowEnd) && pieceDevour){
		    pieces[columnStartN][rowStartN]=null;   
			pieces[columnStartN][rowStartN]=pieces[columnEndN][rowEnd];
		    }
			else
			{
			System.out.println("move invalid, please try to enter another move");			
			}
		   rowStartN=rowEnd;
		   columnStart=columnEnd;

firstLetter=pieces[columnStartN][rowStartN].FindPiece(chessPiece).charAt(0);

What is the charAt(0)? The Piece class should have some methods to return which team it is on. An enum would be good here, but if you don't know how to use enum then have the method return a constant like (0 or 1) or ('b' or 'w') or ("B" or "W").

pieces[columnStartN][rowStartN]=null;   
		pieces[columnStartN][rowStartN]=pieces[columnEndN][rowEnd];

The first line sets an element to null and the second line sets the same element to another element. The first statement is useless because the second one immediately writes over it. I assume this is the code to do a move? Is that right? I don't see any comments in the code describing what the code is supposed to do. Having comments in the code describing what the code is supposed to be doing helps others when they read the code understand its purpose.

for(int column=0;column<pieces.length;column++)
					  for(int row=0;column<pieces[row].length;row++)
						  if(pieces[row][column].FindPiece(chessPiece).equals(chessPiece)){
							  pieces[columnStartN][rowStartN]=pieces[row][column];				           
						       columnStartN=column;
					           rowStartN=row;
						  }
				  




		   // That first paragraph of code is used to find a piece in the array that the user is asking for..
it should compare this.name in the constructor with chessPiece(the user defines)


// this second paragraph, tries to find the first letter of the piece, whether it is black or white. if the piece landed on white and it is black, then the piece would "devour" the white piece. if it landed on black..error ,try again
char firstLetter=' ';
				  char secondLetter=' ';
				  boolean pieceDevour=false;
				   firstLetter=pieces[columnStartN][rowStartN].FindPiece(chessPiece).charAt(0);
				   secondLetter=pieces[columnEndN][rowEnd].FindPiece(chessPiece).charAt(0);
                   if(secondLetter==firstLetter)
                	   pieceDevour=false;
                	   System.out.println("sorry, you cant move onto one of your own pieces");
				  if(firstLetter=='B' & secondLetter=='W')
					  pieceDevour=true;
				  
				  The thrird paragraph wants to check the move it also includes the "pieceDevour" boolean variable.. later on , i would add boolean variables that check whether the move was legit..for example
&& hitsOwnPiece && check
                   
		   if(pieces[columnStartN][rowStartN].isMoveValid(columnStartN,rowStartN,columnEndN,rowEnd) && pieceDevour){
		    pieces[columnStartN][rowStartN]=null;   
			pieces[columnStartN][rowStartN]=pieces[columnEndN][rowEnd];
		    }


// This last code i havent finished, i am trying to create a code that would give a check warning. so far i have a code that finds teh king piece, when i have the king piece, i need to run an array on the piece the user chooses and compare it to the kings position.

so for example, if the user chose bishop and moves it to a square that corresponds in diagonal to a king, it should say check!!

i am thinking to add a method in every class piece
		   rowStartN=rowEnd;
		   columnStart=columnEnd;
		   int kingRow=0;
		   int kingColumn=0;
           chessPiece="BKing";
           int c=0;
           int pieceColumn=0;
           int pieceRow=0;
		   for(int column=0;column<pieces.length;column++){
				  for(int row=0;column<pieces[row].length;row++){
			        if(pieces[column][row].FindPiece(chessPiece).equals(chessPiece));
			        pieces[kingColumn][kingRow]=pieces[column][row];
			        
                      
                        

				  }
		   }

here are a few methods that were added recently to my abstract class!!

package il.co.ChessInterface;



abstract public class ChessPiece {
	  
	 abstract public  boolean isMoveValid(int columnStartN, int rowStart, int columnEnd, int rowEnd);
	
	  abstract public void print();

	 abstract public String FindPiece(String chessPiece); 
	 
	 abstract public void isKingThreatened();
	 
	 abstract public boolean checkMate();

   	}

I don't think your "commented" code will compile without errors. There are missing //

find the first letter of the piece

What are the "letters" of a piece? Would it be 'p' for pawn?

pieces[columnStartN][rowStartN].FindPiece(chessPiece)

What does the FindPiece() method return? The name of the method implies the method is doing a search. What can you "Search" for when looking at a specific piece?
The use of FindPiece here is redundant. The array indexed by a row and column is a piece.

I think you need to go back to the desk and do some design work before continuing to write code without any design.

BTW method name's should start with a lowercase letter.

findPiece isnt redundant.

i think i explained why it is necessary ,, it doesnt do harm, i can complete the algorithm with it and thats why it counts

my problem is to create a new method in every chess piece class to check if there is a check.

i want to create a method called check() in every chess piece class.
for example
public boolean pawnCheck()
it should return whether there is a check
i want to import an array of piece[][] into the method and play with until i can find out if pawn checks the king..

do you know if it is possible to build such method with an piece array inside|

Sorry, I don't understand what FindPiece does?
The code you posted:

public String FindPiece(String chessPiece){
	if(chessPiece.equals(name))
		chessPiece=name;
	return chessPiece;

Doesn't do any thing. If the arg(name) equals the chessPiece, then chessPiece is set to the arg that it is equal to. Why do this?
If the arg is not equal chessPiece is not changed.
Then the value of the arg: chessPiece is returned.
Supposed the value of chessPiece was an "X"
if name == "Y" then the method returns an "X"
if name == "X", chessPiece is set to "X" and "X" is returned.
In both cases, "X" is returned

Can you describe the purpose the the FindPiece method?


I think you need to go back to the desk and do some design work before continuing to write code without any design.

no i want to return me chessPiece if it equals to name;

#
if(chessPiece.equals(name))

return chessPiece;

how do i do it| may be i should make the method boolean..returning true. and if it is true..then the chess piece was found and can be used?

What is the purpose of the findPiece() method?

The user types a piece "Bpn1"

i need to find that piece inside the array (array of objects)

in other word, i want to compare Bpn1 with this.name (objects name)

name==Bpn1


After i traced the correct object (Bpn1 in this case), i found its position column and row number and then i am able to manipulate its movement (e.g. check its validity

Was that a definition of what the method findPiece does? Or did you describe some logic that findPiece is used in?

findPiece doesn't really do anything. It returns a String with the same value as was passed as an arg to the method. Why?

it does return string only. but the point it whose string it returns. it looks for the string this.name=string, that the user tries to find..

hard to explain

for(int column=0;column<pieces.length;column++)
					  for(int row=0;column<pieces[row].length;row++)
						  if(pieces[row][column].FindPiece(chessPiece).equals(chessPiece)){
							  pieces[columnStartN][rowStartN]=pieces[row][column];				           
						       columnStartN=column;
					           rowStartN=row;
						  }

i get the row number and column number because of that.. which is really the aim

Will findPiece() EVER return a String that is different from the value of the String that was passed to it as arg?
If it always returns the value of the arg, what useful task does it do?

i am going to modify it a bit tomorrow may be. i got your point,

i think to break the method down a bit.

may be i will tell the method to return true or false and then if it returns true, another method will gain that value and give me the row and column number of the object it found that value inside.


tomorrow i am going to read a bit on polymorphism, inheritance and interfaces and on Saturday, i am going to try to do the work again, this time adding more algorithms to make that chess game work

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.