Reply to mkyong - "Java – How to print a Pyramid"
今天來寫點小東西。
執行結果:
雖然從小寫程式,尤其大學時特別喜歡OOP的概念,但後來離開coding很長一段時間,並且剛好錯過了Java的崛起。多年前當我下定決心重拾寫程式的熱愛、並且從零開始學習Java時,mkyong的部落格正是親切地陪伴著我成長的資源之一。
無意間在Twitter上看到格主發的小問題,也是一樣那麼的親切:
因此我也試著把我的答案寫一寫,當作禮物回贈給他。
有趣的是,愈簡單的問題,似乎愈容易顯現出程式師個人的語法偏好。
謝謝mkyong!
package info.muspoe.fun; import java.util.function.Consumer; import java.util.function.IntFunction; import java.util.stream.IntStream; public class MyPyramids { public static void main(String[] args) { int rows = 10; Consumer<IntFunction<String>> pyramidFactory = mapper -> IntStream.rangeClosed(1, rows) .mapToObj(mapper) .forEach(System.out::println); System.out.println("\n1. Half Pyramid\n"); pyramidFactory.accept("*"::repeat);
System.out.println("\n2. Full Pyramid\n"); pyramidFactory.accept(i -> " ".repeat(rows - i) + " *".repeat(i));
System.out.println("\n3. Full Pyramid (Compact)\n"); pyramidFactory.accept(i -> " ".repeat(rows - i) + "*".repeat(i * 2 - 1));
System.out.println("\n4. Inverted Pyramid\n"); pyramidFactory.accept(i -> " ".repeat(i - 1) + "*".repeat((rows - i) * 2 + 1));
} }
1. Half Pyramid * ** *** **** ***** ****** ******* ******** ********* ********** 2. Full Pyramid * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 3. Full Pyramid (Compact) * *** ***** ******* ********* *********** ************* *************** ***************** ******************* 4. Inverted Pyramid ******************* ***************** *************** ************* *********** ********* ******* ***** *** *
留言