2016-10-25 79 views
-2

對於作業,我有一個問題,要求我以階梯方式打印字符串的字符。如何反覆添加字符到一個字符串Java

//so if String str = "Compute", I should end up with 
C 
o 
    m 
    p 
    u 
    t 
     e 

這是我迄今的工作。

public static void main(String[] args) { 
    int x = 0; 

    String str = "Compile"; 

    for (int z=0;z<str.length();z++) { 
     char ans = str.charAt(x); 
     String inn=" "+ans 
     System.out.println(inn); 
     x++; 
    } 
} 

我真的不知道該從哪裏出發。請幫幫我。

+0

我認爲你的問題需要更具體些,只需說明問題和'我卡住'的代碼blob不是你可能在這裏得到答案的方式。你的代碼是一個很好的嘗試,你幾乎是正確的(好工作!)。更明確地說明你被困在什麼地方或者你的代碼不能做什麼。 – Tanager4

回答

2

添加一個循環在z每個字符之前打印z空間。類似的,

String str = "Compile"; 
for (int z = 0; z < str.length(); z++) { 
    char ans = str.charAt(z); 
    for (int x = 0; x < z; x++) { 
     System.out.print(" "); 
    } 
    System.out.println(ans); 
} 
-1

您需要打印儘可能多的空間作爲當前字母數,這應該現在的工作:

public static void main(String[] args) { 
    int x = 0; 

    String str = "Compile"; 

    for (int z = 0; z < str.length(); z++) { 
     char ans = str.charAt(x); 
     for (int i = 0; i < x; ++i) 
      System.out.print(' '); 
     System.out.println(ans); 
     x++; 
    } 
} 
+0

'for(int i = 0; i

+0

@ElliottFrisch ooopsie,你是對的。固定! – Jezor

+1

'x'與'z'有什麼不同? –

0

試試這個。

String str = "Compile"; 
String spaces = ""; 
for (int z = 0; z < str.length(); z++) { 
    char ans = str.charAt(x); 
    System.out.println(spaces + str.charAt(z)); 
    spaces += " "; 
} 
相關問題