2017-02-16 89 views
0

我试图得到一个单一的线路输出,有点像这样:使用循环在每个数字之间添加一个空格?

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的,所以我不很确定什么。谢谢你的帮助。

+3

'为(字符空间='“;空间<= 9;空间++)'永远不会执行:'空间<= 9'立即假的,因为' ''== 32'。 –

+0

@shmosel我尝试了你的建议并收到了一个输出结果,但得到了这个“333435363738394041” – DPabst

回答

0

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

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

现在你试图增加一个字符,这是没有道理的。你想space是一个等于你需要的空间数量的数字。

2

可以初始化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); 
    } 
} 
0

你只需要一个循环。

参见: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(); 
+0

如果你建立了一次字符串,那么它会更好,就像你需要的那样大。然后可以使用'print(String,int,int)'重载来打印部分字符串。 –

+2

注意字节码中的构造函数调用次数。 –

+0

我的意思是['PrintWriter.write(char [],int,int)'](https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#write(char [ ],%20int,%20int))。总是忘记那里。 –

0

考虑线组成的9份相同的结构的:x-1空间其次是x,其中1 x变化到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); 
} 

的好处之一是,你不必尾随空格。

0

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

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

    } 

} 
相关问题