java - How to decrement a value in a HashMap? -


so have playerid , numwalls each player in board game i'm making. right remove walls when each player uses one, sharing walls.

so figured should make hashmap hold playerid key , numwalls value.

but don't know how decrement keys value when supposed use wall.

i'll show snip out code has issue.

public int getwallsremaining(int i) {     return numwalls; }  public void lastmove(playermove playermove) {     system.out.println("in lastmove... " + playermove);     /**      * if piece moves, update position      */     if(playermove.ismove() == true){          integer player = playermove.getplayerid();          coordinate newloc = new coordinate(playermove.getendrow(), playermove.getendcol());         playerhomes.put(player, newloc);      }     /**      * if wall placed, subtract wall form player placed      * , subtract appropriate neighbors.      */     if(playermove.ismove() == false){         numwalls-=1;         removeneighbor(playermove.getstart(), playermove.getend());      }   } 

here's initialize everything, walls map i'm trying do:

private map<coordinate, hashset<coordinate>> graph;  private int playerid; private int numwalls; private map<integer, coordinate> playerhomes; private map<integer, integer> walls;    @override public void init(logger logger, int playerid, int numwalls, map<integer, coordinate> playerhomes) {       this.playerid = playerid;     this.walls = new hashmap<integer, integer>();     this.numwalls = numwalls;     this.playerhomes = playerhomes;     this.graph = new hashmap<coordinate, hashset<coordinate>>();     walls.put(playerid,numwalls);      for(int r = 0; r <= 10; r++){         for(int c = 0; c <= 10; c++){             hashset<coordinate> neighbors = new hashset<coordinate>();                  if(r > 0){                     neighbors.add(new coordinate(r - 1, c));                  }                 if(r < 8){                      neighbors.add(new coordinate(r + 1, c));                  }                 if(c > 0){                     neighbors.add(new coordinate(r, c - 1));                  }                 if(c < 8){                     neighbors.add(new coordinate(r, c + 1));                  }             graph.put((new coordinate(r,c)), neighbors);         }     } } 

you can see in lastmove method decrement walls 1. problem. want decrement specified playerid numwall 1. have works 1-player only. need work 4-players.

a hashmap can contain objects (not primitives) must insert integer value mapped.

since integer immutable class can't directly modify value, need replace discarding old value, like:

hashmap<player, integer> walls = new hashmap<player,integer>();  int currentwalls = walls.get(player); walls.put(player, currentwalls-1); 

Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -