[英]How to for loop with TreeMap in Java
I've been trying to print out a Map to a string but at the same time adding additional item in the process.我一直在尝试将 Map 打印到字符串,但同时在此过程中添加了其他项目。 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?
这就是我想要实现的目标:“---\\n---\\n---\\n”但它返回的方式如下:“\\n---\\n---\\n- --”有人知道如何解决这个问题吗?
//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();
0 is divisible by 3. In the initial state, your for loop executes the if statement because 0 % 3 == 0
is true
. 0 可被 3 整除。在初始状态,您的 for 循环执行 if 语句,因为
0 % 3 == 0
为true
。 Change your if to this:将您的 if 更改为:
if(position != 0 && position % 3 == 0)
Or you can start position from 1 and handle the 0th input by yourself before the for loop.或者您可以从 1 开始位置并在 for 循环之前自己处理第 0 个输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.