我想格式化代码的输出,以便每个循环都有一个额外的空格。
示例:
names[4] = "bob", "mark", "james", "frank";
for (int i = 0; i < 4; i++){
System.out.println("Hello, my name is " + names[i]")
}
我希望输出为:
Hello, my name is bob
Hello, my name is mark
Hello, my name is james
Hello, my name is frank
这只是我整个代码的一个小样本,但我必须使用大量的名称来做这个,所以我不能一行一行地放空格。有没有办法根据每个循环关联多少个空格?
答案 0 :(得分:3)
简单,首先使它成为一个print语句(而不是println,它在最后创建一个新行),然后在最后连接一个包含1个空格的字符串,如下所示:
System.out.print("Hello, my name is " + names[i] + " ");
编辑所以你要做的就是按原样打印你的语句,然后在你当前的for循环中再次循环,并打印空格作为当前循环数的次数,例如:< / p>
names[4] = "bob", "mark", "james", "frank";
for (int i = 0; i < 4; i++)
{
for(int k = 0; k < i; k++)
{
System.out.print(" ");
}
System.out.println("Hello, my name is " + names[i]);
}
编辑更顺畅的方式。
names[4] = "bob", "mark", "james", "frank";
String space = "";
for (int i = 0; i < 4; i++)
{
System.out.println(space + "Hello, my name is " + names[i]);
space += " ";
}
希望这有用。 :d
答案 1 :(得分:1)
这是一种更优雅的方式:
names[4] = "bob", "mark", "james", "frank";
spaces = " "; // as many as necessary.
for (int i = 0; i < 4; i++) {
System.out.println(spaces.substring(0, i) +
"Hello, my name is " + names[i]);
}