如何在Java中使用TreeMap进行for循环。

huangapple go评论63阅读模式
英文:

How to for loop with TreeMap in Java

问题

//this is my TreeMap
{
    board.put(0, "-");
    board.put(1, "-");
    board.put(2, "-");
    board.put(3, "-");
    board.put(4, "-");
    board.put(5, "-");
    board.put(6, "-");
    board.put(7, "-");
    board.put(8, "-");
}

//this is the part I'm trying to work on
StringBuilder result = new StringBuilder();
for (position = 0; position <= 8; position++) {
    if (position % 3 == 0) {
        result.append("\n");
    }
    result.append(board.get(position));
}
return result.toString();
英文:

I've been trying to print out a Map to a string but at the same time adding additional item in the process. This is what I'm trying to achieve this: "---\n---\n---\n" But some how it returns like this: "\n---\n---\n---"
Anyone have any idea how to fix this?

  //this is my TreeMap
   {
        board.put(0,&quot;-&quot;);
        board.put(1,&quot;-&quot;);
        board.put(2,&quot;-&quot;);
        board.put(3,&quot;-&quot;);
        board.put(4,&quot;-&quot;);
        board.put(5,&quot;-&quot;);
        board.put(6,&quot;-&quot;);
        board.put(7,&quot;-&quot;);
        board.put(8,&quot;-&quot;);
    }

//this is the part I&#39;m trying to work on
StringBuilder result = new StringBuilder();
        for ( position = 0; position &lt;= 8; position++) {
            if(position % 3 == 0){
                result.append(&quot;\n&quot;);
            }
            result.append(board.get(position));
        }
        return result.toString();

答案1

得分: 1

0 可被 3 整除。在初始状态下,您的 for 循环执行 if 语句,因为 0 % 3 == 0true。将您的 if 更改为以下内容:

if (position != 0 && position % 3 == 0)

或者您可以从 1 开始计算 position,并在 for 循环之前自行处理第 0 个输入。

英文:

0 is divisible by 3. In the initial state, your for loop executes the if statement because 0 % 3 == 0 is true. Change your if to this:

if(position != 0 &amp;&amp; position % 3 == 0)

Or you can start position from 1 and handle the 0th input by yourself before the for loop.

huangapple
  • 本文由 发表于 2020年9月9日 16:57:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/63808196.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定