• Post Reply Bookmark Topic Watch Topic
  • New Topic

Comparing Arrays  RSS feed

 
Kevin Behr
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey all - so I am creating a non-graphical version of the game Mastermind (which entails guessing a secret color code within the fewest amount of tries possible - here is a link containing an example [http://www.irt.org/games/js/mind/]).

Now, I have three arrays:

String board[8][4];
String clues[8][4];
String useCode[4];

board clues useCode

xxxx oooo ROBG
xxxx oooo
xxxx oooo
xxxx oooo
xxxx oooo
xxxx oooo
xxxx oooo
ROYB BBWo

The game is played from the bottom of the board up, and i almost have a complete working version but I am having trouble comparing board[][] with useCode[] to determine clues[][]. I have gotten output to be either:

ROYB WWWW
or
ROYB oooo

Can you please look at my code for trying to compare these arrays? Again, B (or black) is if the guessed color is the right color in the right place. W (or white) is if the color is not in the right place, but was chosen as a guess. If the right color was not guessed, the board stays as 'o'. Here is the code:



bTally[6] contains a count of how many times each color on the board was chosen, and cTally[6] contains a count of how many times each color in useCode was chosen.

For example:

bTally- 1,1,1,0,1,0
cTally- 1,1,0,1,1,0

(representing red, orange, yellow, green, blue, purple)

Thanks!
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think your comparison problem is in this line...

if(board[row][m] == useCode[m])

The == operator compares values. For objects like Strings, this means it compares references. So == will only tell you whether the same String object is being referenced, and not whether the two String representations are the same.

When comparing Strings for "equality," you should use the equals method. For example...

if( (board[row][m]).equals(useCode[m]) )
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're definitely learning good things by writing your own, but unless you get points for doing it, see if you can use Arrays.equals(arr1, arr2)
 
Kevin Behr
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys, I trying out what you said and am definitely having more success. I will be sure to post the finished version!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!