簡體   English   中英

需要幫助進行特定的Java打印

[英]Need help for a specific java printing

所以我有這個程序:

for(int i=1;i<=5;i++){ 
    int y=(int)Math.pow(4,i); 
    System.out.println(y);
}

我如何像這樣打印它:

   4
  16
  64
 256
1024 

(在一個數字之前,它應該是3個空格,2個數字2個空格,3個數字1個空格)。

謝謝:D

System.out.printf("%4d\n", y);
System.out.format("%4d\n", y);

唯一要注意的是,如果將循環更改為生成大於4位數字的數字(例如,i <= 7),則會得到:

   4
  16
  64
 256
1024
4096
16384

然后,您需要計算將產生的最大數字中的位數:

final int MAX_LOOP = 7;

for(int i=1; i<= MAX_LOOP; i++){
    int y=(int)Math.pow(4,i);
    System.out.format("%" + MAX_LOOP + "d\n", y);
}

結果:

    4
   16
   64
  256
 1024
 4096
16384

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM