簡體   English   中英

在Java中使用for循環打印星號

[英]Printing asterisks using for loops in java

在python中打印

******
 *****
  ****
   ***
    **
     *

     *
    **
   ***
  ****
 *****
******

我們將編寫以下代碼:

for e in range (11,0,-1):
    print((11-e) * ' ' + e * '*')

print ('')
for g in range (11,0,-1):
    print(g * ' ' + (11-g) * '*')

我的問題是,這也可以用Java完成嗎? Java不允許您將字符串乘以(int)倍,例如4 * " " ,那么我們如何在Java中實現呢?

簡明扼要:

    // top half..
    for (int i=11;i>0;i--){
        for (int a=0;a<11-i;a++){
            System.out.print(' ');
        }
        for (int b=0;b<i;b++){
            System.out.print('*');
        }
        System.out.println();
    }
public class Loops {

  public static void main(String[] args) {
      //print first half
      for(int i = 0; i < 6; i++) {
          printChar(' ', i);
          printChar('*', 6-i);
          System.out.println();
      }        

      //print second half
      for(int i = 0; i <= 6; i++) {
         printChar(' ', 6-i);
         printChar('*', i);
         System.out.println();
      }
      System.out.println();
    }

    //helper function to print a char n specific times
    private static void printChar(char ch, int n) {
        for(int i = 0; i < n; i++) {
            System.out.print(ch);
        }
    }

}

要在Java中多次運行一個字符串,可以使用for循環。

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

yournum是您想要的空格數

這是一個Core Java解決方案,可以使用單個for循環生成整個輸出:

String before = "", after = "";

for (int i=0; i < 6; ++i) {
    String starRepeat = String.format("%0" + (6-i) + "d", 0).replace("0", "*");
    String spaceRepeat = (i>0) ? String.format("%0" + i + "d", 0).replace("0", " ") : "";
    String line = spaceRepeat + starRepeat;

    if (i == 0) {
        before = line;
        after = line;
    }
    else {
        before = before + "\n" + line;
        after = line + "\n" + after;
    }
}

System.out.println(before + "\n\n" + after);

輸出:

******
 *****
  ****
   ***
    **
     *

     *
    **
   ***
  ****
 *****
******
    IntStream.range(0, 6).forEach(i -> {
        IntStream.range(0, i)
                .forEach(t -> System.out.print(" "));
        IntStream.range(0, 6 - i)
                .forEach(t -> System.out.print("*"));
        System.out.println();
    });

Java8您可以使用Stream來執行相同的操作。 使用IntStream進行rangeprintln

如果您願意使用:Commons Lang StringUtils ...使用Commons Lang StringUtils.repeat()可以幫助您重復一個字符串...例如:

StringUtils.repeat("*", 3) //produces ***

您可以在字符串上添加要打印的消息,然后通過System.out.println(message);打印出字符串值System.out.println(message);

暫無
暫無

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

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