【问题标题】:Add a space between every number using loops?使用循环在每个数字之间添加一个空格?
【发布时间】:2025-12-19 00:50:01
【问题描述】:

我正在尝试输出一行,看起来有点像这样:

1 2  3   4    5     6      7       8        9 

每次增加一个空格。 我需要使用 for 循环来完成,最好使用嵌套的 for 循环。 到目前为止,这是我的代码(在运行时,即使使用方法调用也不会打印。)

public static void outputNine()
{
    for(int x=1; x<=9; x++)
    {
        for(char space= ' '; space<=9; space++)
        {
            System.out.print(x + space);
        }
    }
}

我知道我做错了什么,但我对 java 还很陌生,所以我不太确定是什么。谢谢你的帮助。

【问题讨论】:

  • for(char space= ' '; space&lt;=9; space++) 永远不会执行:space &lt;= 9 立即为假,因为' ' == 32
  • @shmosel 我尝试了你的建议并收到了输出但得到了这个“333435363738394041”

标签: java for-loop nested


【解决方案1】:

您可以只初始化一次space,然后打印数字,并为每个数字打印空格:

char space = ' ';
for(int x=1; x<=9; x++)
{
    System.out.print(x);
    for(int i = 0 ; i < x ; i++)
    {
        System.out.print(space);
    }
}

【讨论】:

    【解决方案2】:

    现在你正试图增加一个字符,这没有意义。您希望space 是一个与您需要的空格数相等的数字。

    【讨论】:

      【解决方案3】:

      您的循环正在使用' ' 的ASCII 值,这不是您想要的。您只需要数到当前的x。用这个替换你的内部循环:

      System.out.print(x);
      for (int s = 0; s < x; s++) {
          System.out.print(" ");
      }
      

      【讨论】:

        【解决方案4】:

        你只需要一个循环。

        参考:Simple way to repeat a String in java

        for (int i = 1; i <= 9; i++) {
            System.out.printf("%d%s", i, new String(new char[i]).replace('\0', ' '));
        }
        

        输出

        1 2 3 4 5 6 7 8 9

        或者更理想的是,

        int n = 9;
        char[] spaces =new char[n];
        Arrays.fill(spaces, ' ');
        PrintWriter out = new PrintWriter(System.out);
        
        for (int i = 1; i <= n; i++) {
            out.print(i);
            out.write(spaces, 0, i);
        }
        out.flush();
        

        【讨论】:

        • 如果你建立一次字符串会更好,只要你需要它。然后您可以使用print(String, int, int) 重载来打印部分字符串。
        • 我的意思是PrintWriter.write(char[], int, int)。永远忘记那在哪里。
        • @AndyTurner 正要说,那个方法调用听起来不太熟悉
        • @GrzegorzGórkiewicz 不仅仅是构造函数调用,replace("\0", " ") 会非常慢,因为它使用正则表达式。 replace('\0', ' ') 会好很多。
        • @AndyTurner 更好吗?
        【解决方案5】:

        认为该行由相同结构的 9 个部分组成:x-1 空格后跟 x,其中 x 从 1 变为 9。

        /*
        0 space + "1"
        1 space + "2"
        2 spaces + "3"
        ...
        */
        
        int n = 9;
        for (int x = 1; x <= n; x++) {
            // Output x - 1 spaces
            for (int i = 0; i < x - 1; i++) System.out.append(' ');
            // Followed by x
            System.out.print(x);
        }
        

        这种方法的一个好处是您没有尾随空格。

        【讨论】:

          【解决方案6】:

          请找到我的简单解决方案:)

          public class Test {
          
              public static void main(String args[]) {
                  for (int i = 1; i <= 9; i++) {
                      for (int j = 2; j <= i; j++) {
                          System.out.print(" ");
                      }
                      System.out.print(i);
                  }
          
              }
          
          }
          

          【讨论】:

            最近更新 更多