コツコツ学習ブログ

プログラマのweb上のメモ的なもの

制御構造の応用

ネストとは

分岐や繰返しの制御構造の中に別の制御構造を含めること。

以下は九九計算を出力するサンプルプログラム。

public class Main {
    public static void main(String args[]) {
        for (int a = 1; a < 10; a++) {
            for (int b = 1; b < 10; b++) {
                System.out.print(a * b);
                System.out.print(" ");
            }
            System.out.println();
        }
    }
}

繰返しの中断

break文

繰返しを囲んでいる内側の繰返しブロックが即座に中断される。 下記サンプルでは、1,2まで出力されて処理が終了する

public class Main {
    public static void main(String args[]) {
        for (int a = 1; a < 10; a++) {
            if (a == 3) {
                break;
            }
            System.out.println(a);
        }
    }
}

continue文

今の周回を中断して、同じ繰返しの次の周回に進む 下記サンプルでは、3以外の1から9までの数字が出力される。

public class Main {
    public static void main(String args[]) {
        for (int a = 1; a < 10; a++) {
            if (a == 3) {
                continue;
            }
            System.out.println(a);
        }
    }
}

switch文のサンプルプログラム(おまけ)

package com.oseans;

public class Main {
    public static void main(String args[]) {
        System.out.print("[メニュー] 1:検索 2:登録 3:削除 4:変更");
        int selected = new java.util.Scanner(System.in).nextInt();
        switch (selected) {
        case 1:
            System.out.print("検索します");
            break;
        case 2:
            System.out.print("登録します");
            break;
        case 3:
            System.out.print("削除します");
            break;
        case 4:
            System.out.print("変更します");
            break;
     default:
            break;
        }
    }
}

おまけ2

制御構文を使用した数当てゲーム

package com.oseans;

public class Main {
    public static void main(String args[]) {
        System.out.print("数当てゲーム☺️");
        //0から9までの乱数を発生させる
        int ans = new java.util.Random().nextInt(10);
        System.out.println("正解は" + ans);
        for (int i = 0; i < 5; i++) {
            System.out.print("0-9の数字を入力してください");
            int num = new java.util.Scanner(System.in).nextInt();
            if (num == ans) {
                System.out.print("正解☺️");
                break;
            } else {
                System.out.print("外れ☺️");
            }
        }
        //ゲーム終了
        System.out.print("ゲームを終了します");
    }
}