Java 嵌套循环:缩进文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36707713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Nested loops: Indent text
提问by bryan callahan
Can anybody help me solve this problem?
有人可以帮我解决这个问题吗?
Print numbers 0, 1, 2, ..., userNum as shown, with each number indented by that number of spaces. For each printed line, print the leading spaces, then the number, and then a newline. Hint: Use i and j as loop variables (initialize i and j explicitly). Note: Avoid any other spaces like spaces after the printed number. Ex: userNum = 3 prints:
如图所示打印数字 0, 1, 2, ..., userNum,每个数字缩进该数量的空格。对于每个打印的行,打印前导空格,然后是数字,然后是换行符。提示:使用 i 和 j 作为循环变量(显式初始化 i 和 j)。注意:在打印的数字后避免任何其他空格,如空格。例如:userNum = 3 打印:
The code given is as follows:
给出的代码如下:
public class NestedLoop {
public static void main (String [] args) {
int userNum = 0;
int i = 0;
int j = 0;
/* Your solution goes here */
return;
}
}
Any suggestions would be appreciated. Thank you.
任何建议,将不胜感激。谢谢你。
采纳答案by Michael
I don't think i
and j
are necessary in that sense...
我不认为i
并且j
在这个意义上是必要的......
for (int i = 0; i <= userNum; i++) {
for (int j = 0; j < i; j++) {
System.out.print(" ");
}
System.out.println(i);
}
回答by RobertB922
This is a little late but I am doing this same challenge in zybooks for school. The above code marked solved is a little off. Using that code places a space at the beginning of the iteration so it should look more like this so the "whitespace" doesn't differ and because "int i" and "int j" were already defined in the main string...
这有点晚了,但我正在学校的 zybooks 中做同样的挑战。上面标记为已解决的代码有点偏离。使用该代码在迭代开始时放置一个空格,因此它应该看起来更像这样,因此“空白”不会有所不同,并且因为“int i”和“int j”已经在主字符串中定义...
for (i = 0; i < userNum; i++) {
for (j = 1; j < i; j++) {
System.out.print(" ");
}
System.out.println(i);
}
Remove the "int" from both "i" & "j" because they have already been defined in your main string. You also have to make "j = 1" otherwise it will put a space before 0 which will have a whitespace difference. Hope this helps anyone else who comes across this challenge.
从“i”和“j”中删除“int”,因为它们已在您的主字符串中定义。您还必须使 "j = 1" 否则它将在 0 之前放置一个空格,这将产生空白差异。希望这可以帮助遇到此挑战的任何其他人。
回答by Sen GY
for (i = 0; i <= userNum; i++) {
for (j = 0; j < i; j++) {
System.out.print(" ");
}
System.out.println(i);
}