java 中的额外空格

Extra whitespaces in java

我想格式化我的代码输出,以便每个循环都有一个额外的空格。

示例:

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

这只是我整个代码的一小部分示例,但我必须使用大量名称来执行此操作,所以我不能只是逐行放置空格。有没有办法根据每个循环关联多少个空格?

简单,先把它做成打印语句(不是println,它在末尾换行),然后在末尾连接一个包含1 space的字符串,像这样:

System.out.print("Hello, my name is " + names[i] + " ");

EDIT 所以你想做的是按原样打印你的语句,然后在你当前的 for 循环中再次循环并打印 spaces 次数作为当前循环编号,例如:

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

这里有一个更优雅的方法:

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]);
}