2016-11-15 12 views
0

1から昇順に数を数えようとしていますが、各行に先行スペースを追加する必要があります。最初の行にスペースがなく、2番目の数字に1スペース、第(n + 1)番目の番号のための第3行およびn個のスペースを含む。String.formatを使用して先行スペースの値を表示するにはどうすればよいですか?

例えばユーザ入力値4は、consleで予想される出力はするかどう:enter image description here私はいくつかの研究を行っている

、私はそれを把握することができませんでした。私はそれがString.formatメソッドに関連していると思います。何か案は?あなたの努力は非常に高く評価されます!

 int c = 0 ; 
     int num = input.nextInt(); 
     input.close(); 
     while (c < num) 
     { 
      c++; 
     System.out.println(String.format("%"+3+"s",c)); //this code gives the same length of leading space on everyline which is not what i want. 

     } 
+0

まあ、静的なスペースの数は%3sです。 – AxelH

答えて

3
public static void main(String[] args) { 
    Scanner input=new Scanner(System.in); 
     int c = 0 ; 
    int num = input.nextInt(); 
    input.close(); 
    while (c < num) 
    { 
     c++; 
    System.out.println(String.format("%"+c+"s",c)); 
    } 
} 

代わりに3ユースCここで

2

の、これがどのように動作するかをお見せするための簡単なループです:

for(int i = 1; i < 10; ++i){ 
    System.out.format("%"+i+"s\n", String.valueOf((char)(i+'a'-1))); 
} 

Basicly、これはどこのフォーマット%の#Sを作成します。 #を必要な番号に更新します。

は私がSystem.out.formatを使用していますがString.formatを使用することができるだけでなく

/!\このフラグへの最小値は1

出力

a 
b 
    c 
    d 
    e 
    f 
     g 
     h 
     i 
+1

限界についての良い点 – xenteros

1

一つの解決策を追加することができスペースを新しい番号ごとにStringBuilderに追加します。

StringBuilder spaces = new StringBuilder(); 
Scanner sc = new Scanner(System.in); 
int userChoice = 0; 
while(userChoice != -1){ 
    userChoice = sc.nextInt(); 
    System.out.print(spaces.toString()); 
    System.out.print(userChoice); 
    System.out.println(); 
    spaces.append(" "); 
} 
関連する問題