2015-12-07 35 views
0
public class NestedLoopPattern { 
    public static void main(String[] args) { 
     final int HASHTAG_AMMOUNT = 6; 

     for (int i=0; i < HASHTAG_AMMOUNT; i++) { 
      System.out.println("#"); 
      for (int j=0; j < i; j++) { 
       System.out.print(" "); 
      } 
      System.out.println("#"); 
     } 
    } 
} 

我應該讓這種模式與嵌套循環,但上面我不能代碼,如何使循環模式在Java中

## 
# # 
# # 
# # 
# # 
#  # 

我只是不斷收到這是我的輸出:

# 
# 
# 
# 
# 
    # 
# 
    # 
# 
     # 
# 
     # 

回答

1

你錯誤地分別致電System.out.println()第一個哈希標記,這是打印一個換行符,你不想要它。只是,電話更改爲System.out.print(),你應該是好去:

public class NestedLoopPattern { 
    public static void main(String[] args) { 
     final int HASHTAG_AMMOUNT = 6; 

     for (int i=0; i < HASHTAG_AMMOUNT; i++) { 
      // don't print a newline here, just print a hash 
      System.out.print("#"); 
      for (int j=0; j < i; j++) { 
       System.out.print(" "); 
      } 
      System.out.println("#"); 
     } 
    } 
} 

輸出:

## 
# # 
# # 
# # 
# # 
#  # 
+0

非常感謝你! – thesaitguy2017

1

的問題是,在外部循環的每次迭代,你打印兩個新行。所以你打印第一個「#」,然後是一個換行符,然後是其餘的行。

您需要將第一個System.out.println("#");更改爲System.out.print("#");,然後才能正常工作。

所以,你應該你的代碼改成這樣:

public class NestedLoopPattern { 
    public static void main(String[] args) { 
     final int HASHTAG_AMMOUNT = 6; 

     for(int i = 0; i < HASHTAG_AMMOUNT; i++) { 
      System.out.print("#"); //No need to print a newline here 

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

      System.out.println("#"); 
     } 
    } 
} 

這會給你的預期輸出:

## 
# # 
# # 
# # 
# # 
#  # 
+0

非常感謝你! – thesaitguy2017

0

解決方案:

IntStream.rangeClosed(1, MAX) 
       .forEach(i -> IntStream.rangeClosed(1, i + 1) 
         .mapToObj(j -> j == i + 1 ? "#\n" : j == 1 ? "# " : " ") 
         .forEach(System.out::print) 
       );