英文:
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,"-");
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();
答案1
得分: 1
0 可被 3 整除。在初始状态下,您的 for 循环执行 if 语句,因为 0 % 3 == 0
为 true
。将您的 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 && position % 3 == 0)
Or you can start position from 1 and handle the 0th input by yourself before the for loop.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论