-3

I want to display tic tac toe board. Something like that:

XXX
XXX
XXX

Is it possible to use for each to achieve that? I tried to do some:

    Map<Integer, Tile> board = generateBoard();

    for (Map.Entry<Integer, Tile> entry: board.entrySet()){
        System.out.print(entry.getValue().getSign());
    }

    board.forEach((k,v) -> {
        int i = 1;
        if(i % 3 == 0){
            System.out.println();
        }
        System.out.print(v.getSign());
        i++;
    });

But my output is incorrect. Could you give me any output to achieve me this output?

Ice
  • 1,783
  • 4
  • 26
  • 52
  • 2
    What do you mean by incorrect? Also could you please provide a [minimum, complete, verifiable, example](https://stackoverflow.com/help/mcve)? – Chris Jun 28 '17 at 22:50
  • 1
    Read the code you wrote in plain English. *Set i equal to one. Test to see if one modulo three is zero, and if so call println. Call print, and then add one to i. Then go back to Set i equal to one.* Does that seem right to you? – Ken White Jun 28 '17 at 22:53

3 Answers3

1

One obvious problem is that i isn't incremented because you're redefining it on each iteration. Unfortunately, labmdas and stateful variables don't mix well. I would suggest using a regular for loop instead:

int i = 0;
for (Tile tile : board.values()) {
    System.out.print(tile.getSign());
    if (++i % 3 == 0) {
        System.out.println();
    }
}
shmosel
  • 49,289
  • 6
  • 73
  • 138
0

Two things:

  1. Your i will never increment, as it is declared within the loop. It will always be 1.
  2. If you have "k" (the index) why are you creating a new index?

Remove i and replace it with k and see if that helps.

UnkJester
  • 19
  • 3
0

Variables referenced inside lambda from outside the lambda must be Effectively Final or final. This prevents you from easily incrementing a counter remembering where you are up to.

Assuming that the integer key in your map, is the slot number you can do this.

 board.forEach((k,v) -> {
        System.out.print(v.getSign());
        if(k % 3 == 0){
            System.out.println();
        }
    });
Ryan Leach
  • 4,262
  • 5
  • 34
  • 71
  • 1
    Variables *inside* lambdas are **not** effectively final. Variables *outside* lambdas may only be referenced *within* them if they're final or effectively final. – shmosel Jun 29 '17 at 03:28
  • Thanks. I've edited to make the language I used more clear. – Ryan Leach Jun 29 '17 at 03:41