简体   繁体   中英

HashMap not functioning as expected

I have made a 3 x 3 box matrix. Clicking on either one of the box adds the element to the hashmap Eg , click on 1st box adds "imageView1" as a key and "true" as a value to the hashmap.

There are two players , hence two hashmaps player1 and player2.

player1.put("imageView1","true");

So when either of the player clicks on the box , the respective box name is added to the respective hashmap.

Then to check if the player has won

  if(player1.containsKey("imageView1") 
     &&player1.containsKey("imageView2")
     &&player1.containsKey("imageView3")){
        return true;
    }

But this doesnt work . Can you help me with it? Note: I didnt put the whole algorithm .. I just checked 1 condition (ie. if 1 2 3 are checked then player 1 won, like tic tac toe

Heres are the files

MainActivity.java(original) ( http://pastebin.com/AtypDtuC )

MainActivity.java(condensed) ( http://pastebin.com/gJCud9WE )

Content_Main.xml ( http://pastebin.com/vsWd0Jii )

Your code seems fine but I would suggest inspecting what

getResources().getResourceName(view.getId())

is putting inside your map. Specifically you should confirm that:

getResources().getResourceName(view.getId()).equals("imageView1")
getResources().getResourceName(view.getId()).equals("imageView2")
getResources().getResourceName(view.getId()).equals("imageView3")
getResources().getResourceName(view.getId()).equals("imageView4")
...
getResources().getResourceName(view.getId()).equals("imageViewN")

is true at least once. Ie you need to ensure that you are putting in Strings which are exactly the same as when you call .contains() , otherwise you will never get a match with .contains()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM