LoginSignup
5
2

More than 5 years have passed since last update.

【Java】簡単な模様を描く

Last updated at Posted at 2019-02-06

頭の体操レベルですが、簡単な模様を描くコードを作ってみました。
元々は職場で新人向けの課題として作ったものなので、Java初学者の方にはちょっとした力試しになるかもしれません。

細かな市松模様(チェック)を描画する

出力イメージ

*.*.*.*.*.
.*.*.*.*.*
*.*.*.*.*.
.*.*.*.*.*
*.*.*.*.*.
.*.*.*.*.*
*.*.*.*.*.
.*.*.*.*.*
*.*.*.*.*.
.*.*.*.*.*

コード

  • 出力イメージでは"*"と"."が交互に描画されているので、行番号と列番号を使って出力する文字を1つずつ切り替えています。
/**
 * 細かな市松模様(チェック)を描画する。
 * @param outputSize 描画サイズ(桁数)。
 */
public static void printFineCheckered(int outputSize) {

    // 行方向への移動
    for (int i=0; i<outputSize; i++) {

        // 列方向への移動
        for (int j=0; j<outputSize; j++) {

            if ((i+j)%2==0) {
                System.out.print("*");
            } else {
                System.out.print(".");
            }

        }

        // 改行を入れる
        System.out.print(System.lineSeparator());

    }
}

バツ印を描画する

出力イメージ

*........*
.*......*.
..*....*..
...*..*...
....**....
....**....
...*..*...
..*....*..
.*......*.
*........*

コード

  • 「左上から右下に伸びる線」は簡単に描画できますが、「左下から右上に伸びる線」の条件がパッと出てこない、あるいは間違いやすいかもしれません。
/**
 * バツ印を描画する。
 * @param outputSize 描画サイズ(桁数)。
 */
public static void printCrossMark(int outputSize) {

    // 行方向への移動
    for (int i=0; i<outputSize; i++) {

        // 列方向への移動
        for (int j=0; j<outputSize; j++) {

            if (i==j) {
                // 左上から右下に伸びる線
                System.out.print("*");
            } else if (i+j==outputSize-1) {
                // 左下から右上に伸びる線
                System.out.print("*");
            } else {
                System.out.print(".");
            }

        }

        // 改行を入れる
        System.out.print(System.lineSeparator());

    }
}

市松模様(チェック)を描画する

出力イメージ

  • この画面だと見づらいですが、以下の出力イメージをテキストエディタに貼り付けると、市松模様が分かりやすいと思います。
**..**..**
**..**..**
..**..**..
..**..**..
**..**..**
**..**..**
..**..**..
..**..**..
**..**..**
**..**..**

コード

  • 市松模様は「4行4列」の単位で1つのブロックになっているので、それを発見・理解できるかどうかが一つのカギになりそうです。
  • コードそのものは、以下のようにそれほど難しくはないと思います。
/**
 * 市松模様を描画する。
 * @param outputSize 描画サイズ(桁数)。
 */
public static void printIchimatsu(int outputSize) {

    // 行方向への移動
    for (int i=0; i<outputSize; i++) {

        // 列方向への移動
        for (int j=0; j<outputSize; j++) {

            int rowIndex = i%4;
            int colIndex = j%4;

            if (rowIndex<2 && colIndex<2) {
                System.out.print("*");
            } else if (rowIndex>=2 && colIndex>=2) {
                System.out.print("*");
            } else {
                System.out.print(".");
            }

        }

        // 改行を入れる
        System.out.print(System.lineSeparator());

    }

}
5
2
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2