2017-02-16 88 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); 
     } 

    } 

} 
相關問題